uestc 10 In Galgame We Trust

时间:2021-11-08 02:19:00

题意:求最长的合法括号序列

解:栈+分类讨论

now表示已经算出的序列,且此序列与现在扫描的序列可能能够连接,tmp表示现在扫描到的序列长度

左括号入栈

右括号:1.栈空时:统计当前总长 并且将栈,now,tmp清空

2.栈不空:(1)匹配:tmp+2,弹栈,如果弹栈后栈为空,now=now+tmp相当于把现在算出的和之前算出的连起来,因为此时栈空,已经没有括号挡在两段序列之间

(2)不匹配:now=tmp=0,栈清空

 #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#include<string> using namespace std; int T;
char s[];
char stk[]; bool check(char c1,char c2){
if (c1=='(' && c2==')') return true;
if (c1=='{' && c2=='}') return true;
if (c1=='[' && c2==']') return true;
return false;
} int main(){
scanf("%d",&T);
for (int cas=;cas<=T;cas++){
scanf("%s",s);
int len=strlen(s);
int ans=;
int now=;
int tmp=;
int top=;
for (int i=;i<len;i++){
if (s[i]==')' || s[i]=='}' || s[i]==']'){
if (top> && check(stk[top],s[i])){
tmp+=;
top--;
if (top==){
now+=tmp;
tmp=;
ans=max(ans,now);
}
}
else{
if (top> && !check(stk[top],s[i])){
ans=max(ans,tmp);
top=;
now=;
tmp=;
}
else{
if (top==){
now=now+tmp;
ans=max(now+tmp,ans);
now=tmp=;
}
}
}
}
else{
top++;
stk[top]=s[i];
}
}
ans=max(ans,tmp);
if (top==){
ans=max(ans,now+tmp);
}
if (ans==)
printf("Case #%d: I think H is wrong!\n",cas);
else
printf("Case #%d: %d\n",cas,ans);
}
return ;
}
/*
3
(){[]}
{([(])}
))[{}]] 8
[()(()]{}()) 8
[()(()())
([)(()())
()[(()())
()([()())
()(([)())
()(()]())
()(()()])
()(()())]
*/