CF5C Longest Regular Bracket Sequence

题目来源CodeForces 5C
评测方式RemoteJudge
难度提高+/省选-

题意翻译

给出一个括号序列,求出最长合法子串和它的数量。 合法的定义:这个序列中左右括号匹配

题目描述

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.

输入格式

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 10^{6} .

输出格式

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".

输入输出样例

输入 #1
)((())))(()())
输出 #1
6 2
输入 #2
))(
输出 #2
0 1
#include <bits/stdc++.h>
using namespace std;
const int M = 1e6 + 5;
char s[M];
int n[M];
stack<int> st;
int main()
{
scanf("%s", s + 1);
int l = strlen(s + 1);
int ml = 0, mn = 1;
for (int i = 1; i <= l; i++)
{
if (st.empty() && s[i] == ')')
continue;
if (s[i] == ')')
{
n[i] = i - st.top() + 1 + n[st.top() - 1];
st.pop();
if (n[i] == ml)
mn++;
if (n[i] > ml)
{
ml = n[i];
mn = 1;
}
}
else
st.push(i);
}
printf("%d %d\n", ml, mn);
return 0;
}

评论

此博客中的热门博文

将博客部署到星际文件系统(IPFS)

高中地理必修一知识点总结

一场CF的台前幕后(下)