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".
Examples
Input
)((())))(()())
Output
6 2
Input
))(
Output
0 1
题意:求符合规范的字符串的最大长度和个数
思路:注意左括号和右括号的关系,先从左往右扫一遍,遇到‘(’就加1,遇到‘)’就减一,并且标记该位置,说明匹配了一对括号。然后从右往左扫一次,遇到‘)’加一,遇到‘(’减一,同样标记该位置,最后在遍历一次标记,找到含有标记的最长的序列。
#include<iostream>
#include<string.h>
#include<stack>
using namespace std;
const int MAX = 1000050;
int N;
int maxl;
int cnt;
int dp[MAX];
int mark[MAX];
void solve(string s)
{
maxl = 0;
cnt = 0;
memset(dp, 0, sizeof(dp));
memset(mark, 0, sizeof(mark));
int len = s.length();
if (s[0] == '(')
dp[0] = 1;
for (int i = 1; i < len; i++)
{
if (s[i] == '(')
dp[i] = dp[i-1] + 1;
else
{
dp[i] = dp[i-1] - 1;
if (dp[i] >= 0)
mark[i] = 1;
else
dp[i] = 0;
}
}
memset(dp, 0, sizeof(dp));
if (s[len - 1] == ')')
dp[len - 1] = 1;
for (int i = len - 2; i >= 0; i--)
{
if (s[i] == ')')
dp[i] = dp[i+1] + 1;
else
{
dp[i] = dp[i+1] - 1;
if (dp[i] >= 0)
mark[i] = 1;
else
dp[i] = 0;
}
}
int l = 0;
for (int i = 0; i < len; i++)
{
if (mark[i] == 1)
l++;
else
{
if (l != 0)
{
if (maxl < l)
{
maxl = l;
cnt = 1;
}
else if (maxl == l)
cnt++;
l = 0;
}
}
if (i == len - 1)
{
if (l != 0)
{
if (maxl < l)
{
maxl = l;
cnt = 1;
}
else if (maxl == l)
cnt++;
}
}
}
}
int main()
{
string s;
while (cin >> s)
{
solve(s);
if (maxl == 0)
cout << 0 << ' ' << 1 << endl;
else
cout << maxl << ' ' << cnt << endl;
}
return 0;
}