The following figure shows how many matching brackets exist between [a, B] in M queries (including a, B: process Two arrays R [I] (representing the number of matched right brackets between 1 and I ), L [I] (represents the number of unmatched left parentheses between 1 and I ). We need to calculate the number of matching parentheses between [a, B], first use R [B]-R [A-1], but masking is more likely that the right brackets between A and B are matched between [1, A-1], then minus L [A-1], but minus this part, it is also possible that it is matched in the range [B + 1, Len]. To add the value that should not be subtracted from this part, you only need to add min (L [a] ~ L [B. If the interval is the minimum value, use the line segment tree.
Code:
#include <iostream>#include <cstdio>#include <cstring>#define N 1000010using namespace std;#define L(x) (x)<<1#define R(x) (x)<<1|1int m,len,r[N],l[N];char bra[N];struct node{ int ll,rr,v;}t[N*6];int bulid(int x,int y,int idx){ t[idx].ll=x,t[idx].rr=y; if(x==y) return t[idx].v=l[x]; int mid=(x+y)/2; return t[idx].v=min(bulid(x,mid,L(idx)),bulid(mid+1,y,R(idx)));}int query(int x,int y,int idx){ if(x==t[idx].ll && y==t[idx].rr) return t[idx].v; int mid=(t[idx].ll+t[idx].rr)/2; if(x>mid) return query(x,y,R(idx)); if(y<=mid) return query(x,y,L(idx)); return min(query(x,mid,L(idx)),query(mid+1,y,R(idx)));}int main(){ scanf("%s",bra); len=strlen(bra); int tmp=0; for(int i=1;i<=len;i++) { r[i]=r[i-1]; if(bra[i-1]=='(') tmp++; else if(tmp) r[i]++,tmp--; l[i]=tmp; } bulid(1,len,1); scanf("%d",&m); while(m--) { int a,b; scanf("%d%d",&a,&b); if(a==b) {cout<<0<<endl;continue;} int ans=min(r[b]-r[a-1],r[b]-r[a-1]-l[a-1]+query(a,b,1)); cout<<ans*2<<endl; } return 0;}
Codeforces generation C. sereja and brackets [Line Segment tree]