Codeforces generation C. sereja and brackets [Line Segment tree]

Source: Internet
Author: User
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.