Codeforces Round #603 (Div. 2)E
http://codeforces.com/contest/1263/problem/E
题意:求合法的括号序列
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define lson root<<1,l,midd #define rson root<<1|1,midd+1,r #define pb push_back const int inf=0x3f3f3f3f; const ll INF=1e18; const int M=1e6+6; int tree[M<<2]; int lzmi[M<<2];///最小前缀和 int lzma[M<<2];///最大前缀和 char s[M]; void up(int root){ tree[root]=tree[root<<1]+tree[root<<1|1]; lzma[root]=max(lzma[root<<1],tree[root<<1]+lzma[root<<1|1]);///右区间来选前缀时要考虑到左区间带进来的贡献 lzmi[root]=min(lzmi[root<<1],tree[root<<1]+lzmi[root<<1|1]); } void update(int p,int v,int root,int l,int r){ if(l==r){ tree[root]=lzmi[root]=lzma[root]=v; return ; } int midd=(l+r)>>1; if(p<=midd) update(p,v,lson); else update(p,v,rson); up(root); } int main(){ int n; scanf("%d%s",&n,s); int nowpos=1; for(int i=0;i<n;i++){ if(s[i]=='L') nowpos=max(1,nowpos-1); else if(s[i]=='R') nowpos++; else if(s[i]=='(') update(nowpos,1,1,1,n); else if(s[i]==')') update(nowpos, -1,1,1,n); else update(nowpos,0,1,1,n); ///若全区间和不为0,则证明左括号数和右括号数不等 ///若全区间最小前缀和不为0,则证明至少有一个右括号没有被左括号对应, if(lzmi[1]<0||tree[1]!=0) printf("-1 "); else printf("%d ",lzma[1]); } return 0; }