1. 程式人生 > >Codeforces Round #529 (Div. 3) E. Almost Regular Bracket Sequence (思維)

Codeforces Round #529 (Div. 3) E. Almost Regular Bracket Sequence (思維)

ssis close splay pac gif 思路 www. -s ont

Codeforces Round #529 (Div. 3)

題目傳送門

題意:

給你由左右括號組成的字符串,問你有多少處括號翻轉過來是合法的序列

思路:

這麽考慮:

如果是左括號

1)整個序列左括號個數比右括號多 2

2)在這個位置之前,所有位置的前綴左括號個數都不少於前綴右括號個數

3)在這個位置和這個位置之後,在修改後所有位置的前綴左括號個數減去前綴右括號個數大於2

(這裏這麽想,把左變成右,左-1,右+1)

右括號也是這樣

代碼:

技術分享圖片
#include<bits/stdc++.h>
using namespace std;
const int
N=1e6+10; int a[N],pre[N],post[N]; char s[N]; int n; int main() { while(~scanf("%d",&n)) { scanf("%s",s+1); int x=0; memset(a,0,sizeof(a)); for(int i=1;i<=n;i++) { if(s[i]==() x++; else x--; a[i]
=x; } pre[0]=N,post[n]=N; for(int i=1;i<n;i++) pre[i]=min(pre[i-1],a[i]); for(int i=n-1;i>=0;i--) post[i]=min(post[i+1],a[i]); int ans=0; if(x!=-2&&x!=2) { printf("0\n"); } else{ for(int i=1;i<=n;i++) {
if(s[i]==() { if(pre[i-1]>=0&&post[i]>=2&&x==2) ans++; } else if(pre[i-1]>=0&&post[i]>=-2&&x==-2) ans++; } printf("%d\n",ans); } } }
View Code

Codeforces Round #529 (Div. 3) E. Almost Regular Bracket Sequence (思維)