C. Longest Regular Bracket Sequence

链接

[https://codeforces.com/problemset/problem/5/C]

题意

给一个括号序列,让你找最长合法括号序列,
并输出该长度有多少个

分析

用栈存左括号,一旦遇到右括号就看栈有没有左括号有就标记这两个位置为合法位置。并出栈一个左括号
最后找最长连续的合法位置即可

代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e6+10;
int a[N];
string s;
void solve(){
	memset(a,0,sizeof(a));
	int n=s.length();
	stack<int> st;
	for(int i=0;i<n;i++)
	if(s[i]=='(')
	st.push(i);
	else{
		if(!st.empty()){
			a[i]=1;
			a[st.top()]=1;
			st.pop();
		}
	}
	
	int ma=0,cnt=1,al=0;
	for(int i=0;i<n;i++)
	{
		if(a[i])
	    al++;
	    else{
	    	al=0;
		}
		if(al==ma&&ma!=0)
		cnt++;
		else if(al>ma)
		{
			ma=al;
			cnt=1;
		}
	}
	cout<<ma<<' '<<cnt<<endl;
}
int main(){
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	while(cin>>s){
		solve();
	}
	return 0;
}
posted @ 2019-05-22 17:22  ChunhaoMo  阅读(247)  评论(0编辑  收藏  举报