51nod 1478 括号序列的最长合法子段(栈-括号匹配寻找最长合法子串长度及其个数)

来源:互联网 发布:linux下python mmap 编辑:程序博客网 时间:2024/05/22 07:54

1478 括号序列的最长合法子段
题目来源: CodeForces
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
 收藏
 关注

这里有另一个关于处理合法的括号序列的问题。

如果插入“+”和“1”到一个括号序列,我们能得到一个正确的数学表达式,我们就认为这个括号序列是合法的。例如,序列"(())()", "()"和"(()(()))"是合法的,但是")(", "(()"和"(()))("是不合法的。

这里有一个只包含“(”和“)”的字符串,你需要去找到最长的合法括号子段,同时你要找到拥有最长长度的子段串的个数。


Input
第一行是一个只包含“(”和“)”的非空的字符串。它的长度不超过 1000000。
Output
输出合格的括号序列的最长子串的长度和最长子串的个数。如果没有这样的子串,只需要输出一行“0  1”。
Input示例
)((())))(()())
Output示例
6 2


题解:看多题目了,以为是找所有合法子串个数。想了半天,发现时找最长的。 那么就很简单了,用一个栈维护,将没办法形成匹配的括号及其位置放进一个栈里面,那么最后栈内每两个括号之间就有一个合法串,然后从前往后扫一遍,记录下最长合法串长度及其个数就好了。


代码如下:


#include <cstdio>#include <cstring>#include <algorithm>#include <stack>using namespace std;const int maxn = 1e6+10;struct node{int id;char s;}temp; stack<node> tac;char str[maxn];int main(){while(scanf("%s",str)!=EOF){int len=strlen(str);int Max=0,cnt=1;while(!tac.empty())tac.pop();for(int i=0;i<len;++i){if(str[i]=='('){temp.id=i;temp.s='(';tac.push(temp);}else{if(tac.empty()){temp.id=i;temp.s=')';tac.push(temp);}else{temp=tac.top();if(temp.s==')'){temp.id=i;tac.push(temp);}elsetac.pop();}}}if(tac.empty())Max=len;else{temp=tac.top();int L=len-temp.id-1;Max=L;while(!tac.empty()){temp=tac.top();tac.pop();if(tac.empty()){if(temp.id>Max){Max=temp.id;cnt=1;}else if(temp.id==Max)cnt++;}else{node step=tac.top();L=temp.id-step.id-1;if(L==Max)cnt++;else if(L>Max){cnt=1;Max=L;}}}}if(Max==0)cnt=1;printf("%d %d\n",Max,cnt);}return 0;}



1 0