Description
This is yet another problem dealing with regular bracket sequences.
We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
Input
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.
Output
Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".
Sample Input
)((())))(()())
6 2
))(
0 1
这个题不会做
想不到科学的方法,导致分支太多,太复杂
听了一大神的思路:
先从左for到右 遇到( cun++ 遇到)并且此时cun>0 即该右括号是合法的 vis[右括号]=1
同理 再从右到左 标记所有 合法的左括号
最后把vis数组for一遍 if (vis[i]) cun++; 遇到vis[]==0 就判断是否比max大, 从而最后筛选到最大值和个数
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
char tm[1000000+5];
int vis1[1000000+5];
int ans[500000+5];
int main()
{
scanf("%s",tm+1);
int len=strlen(tm+1);
int i, cun=0;
for (i=1;i<=len;i++)
{
if (tm[i]=='(')
cun++;
if (tm[i]==')')
{
if (cun)
{
vis1[i]=1;
}
cun--;
}
if (cun<0)
cun=0;
}
cun=0;
for (i=len;i>=1;i--)
{
if (tm[i]==')')
cun++;
if (tm[i]=='(')
{
if (cun)
{
vis1[i]=1;
}
cun--;
}
if (cun<0)
cun=0;
}
int ok=0;
cun=0;
int max=0;
for (i=1;i<=len;i++)
{
if (vis1[i]==1)
cun++;
else
cun=0;
if (cun>max) max=cun,ok=1;
else if (cun==max)
ok++;
}
if (max==0) ok=1;
printf("%d %d\n",max,ok);
return 0;
}