Test instructions: The number of strings and longest strings for the longest Rule (' (() ') ' or ' (() ') given a string of parentheses;
Idea: Use the stack to save the opening parenthesis, match the nearest closing parenthesis, and use recursion to roll out the longest string length of each position;
#include <cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<stack>using namespaceStd;stack<int>T;intN,m,len,maxx;intdp[5000100];Charstr[5000100];intMain () { while(SCANF ("%s", str)! =EOF) { inti,j,k; Len=strlen (str); Memset (DP,0,sizeof(DP)); for(i=0; i<len;i++){ if(str[i]=='('){//left bracket in stackT.push (i); } Else{ if(!T.empty ()) { inttemp=T.top (); T.pop (); if(temp) {Dp[i]=dp[temp-1]+i-temp+1;//roll out the longest continuous length () + () } ElseDp[i]=i-temp+1;//when Temp==0} }} Maxx=0; intCnt=0; for(i=0; i<len;i++){ if(maxx<Dp[i]) {Maxx=Dp[i]; CNT=1; } Else if(maxx==Dp[i]) {CNT++; } } if(maxx==0) printf ("0 1\n"); Elseprintf ("%d%d\n", maxx,cnt); } return 0;}
Codeforces 5C longest Regular bracket Sequence