Codeforces Round #626 (Div. 2, based on Moscow Open Olympiad in Informatics) 比赛人数5260
[codeforces 1323C] Unusual Competitions 栈呼之欲出
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
在线测评地址https://codeforces.ml/contest/1323/problem/C
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
C - Unusual Competitions | GNU C++11 | Accepted | 46 ms | 4700 KB |
因B题较难,切换到C题,从匹配角度入手,很快样例通过,提交Wrong answer on pretest 6
错在哪,将题正文中提到的数据,也用了一遍。
找到一组数据
Input:
6
(()))(
Output:
2
数据模拟过程如下
( l=1
(( l=2
(()用栈处理变为( l=1
()用栈处理变为 l=0
) r=1
)( r=1,l=1 进行数据重排,变为() r=0,l=0 对结果影响是2
根据这组数据,引入了栈,发现栈太好用了,解决了两点,一是括号匹配,二是可以位置不连续的数据
在比赛中,在处理不连续位置的数据比较棘手时,栈就象本能反应一样的跳出来,那种感觉太妙了。
很快代码AC.
#include <stdio.h>
#include <string.h>
char s[1000010];
int st[1000010],top=0;//st[]记录左括号位置,只有左括号才能进栈
int ans=0;
int main(){
int n,i,l=0,r=0,pre=0,now=0;//l左括号数量,r右括号数量
scanf("%d%s",&n,s+1);
for(i=1;i<=n;i++)
if(s[i]==')')r++;
else l++;
if(l!=r){//左右括号数量不一致
printf("-1\n");
return 0;
}
l=0,r=0;
s[0]='\0';
for(i=1;i<=n;i++){
if(s[i]==')'){
if(!pre){
if(top&&s[st[top]]=='(')l--,top--;
else pre=i,r++;//pre记录不规则字串起始位置
}else{
r++;
}
}else{//s[i]=='('
st[++top]=i,l++;
if(l==r){
ans+=i-pre+1;//i记录不规则字串结束位置
pre=0,l=0,r=0,top=0;
}
}
}
printf("%d\n",ans);
return 0;
}