CSU 1809 Parenthesis 【前缀和+RMQ】

来源:互联网 发布:redis存储数据大小 编辑:程序博客网 时间:2024/05/01 17:49

Description

Bobo has a balanced parenthesis sequence P=p 1 p 2…p n of length n and q questions.
The i-th question is whether P remains balanced after p ai and p bi  swapped. Note that questions are individual so that they have no affect on others.
Parenthesis sequence S is balanced if and only if:
1.  S is empty;
2.  or there exists balanced parenthesis sequence A,B such that S=AB;
3.  or there exists balanced parenthesis sequence S' such that S=(S').

Input

The input contains at most 30 sets. For each set:
The first line contains two integers n,q (2≤n≤10 5,1≤q≤10 5).
The second line contains n characters p 1 p 2…p n.
The i-th of the last q lines contains 2 integers a i,b i (1≤a i,b i≤n,a i≠b i).

Output

For each question, output " Yes" if P remains balanced, or " No" otherwise.

Sample Input

4 2(())1 32 32 1()1 2

Sample Output

NoYesNo

Hint


/*    题意:给你一个长度为n的括号平衡串和q次询问,每次询问给你a,b,          表示第a个位置和第b个位置的字符交换,如果交换后仍为括号平衡串,          输出Yes,否则输出No    类型:前缀和+RMQ(线段树也行)    分析:1.当左边的字符与右边的字符一样时,交换一定为括号平衡串              2.当左边的字符为')'时,交换一定为括号平衡串.因为一开始是平衡串,          如果左边的字符')'与右边的'('交换,那么此时交换的两个必能匹配为一对,          如果左边的字符')'与右边的')'交换,那么此时交换的两个字符相同,满足1.                    3.当左边的字符为'('时,满不满足和右边位置左括号未匹配的个数有关.          建立前缀和数组a,表示当前位置左括号未匹配的个数,          当遇到左括号时前缀和+1,右括号时前缀和-1,那么由个例推出规律          ( ( ( ) ) )          1 2 3 2 1 0          当左边的'('与右边的交换能满足仍为括号平衡串的必须是在区间[a,b-1]内          的最小值>=2          所以问题转化为求区间[a,b-1]内的前缀和数组最小值是否满足>=2          可以用基于ST的RMQ算法,也可以用线段树求区间最小值*/#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;typedef long long ll;int a[100005];char zi[100000+100];int Min[100005][32];int n;void rmq_init(){    for(int i=1;i<=n;i++){        Min[i][0]=a[i];    }    for(int j=1;(1<<j)<=n;j++){        for(int i=1;i+(1<<j)-1<=n;i++){            Min[i][j]=min(Min[i][j-1],Min[i+(1<<(j-1))][j-1]);        }    }}int rmq(int l,int r){    int k=0;    while((1<<(k+1))<=r-l+1)k++;    return min(Min[l][k],Min[r-(1<<k)+1][k]);}int main(){    int m;    while(scanf("%d%d",&n,&m)!=EOF){        scanf("%s",&zi[1]);        a[0]=0;        for(int i=1;i<=n;i++){            if(zi[i]=='(')a[i]=a[i-1]+1;            else a[i]=a[i-1]-1;        }        rmq_init();        for(int i=1;i<=m;i++){            int b,c;            scanf("%d%d",&b,&c);            if(b>c)swap(b,c);            if(zi[b]==zi[c]||(zi[b]==')'&&zi[c]=='(')){                printf("Yes\n");                continue;            }            if(rmq(b,c-1)>=2)printf("Yes\n");            else printf("No\n");        }    }}












1 0
原创粉丝点击