Parenthesis

禹德水
2023-12-01

/*

Problem G: Parenthesis
Time Limit: 5 Sec Memory Limit: 128 MB
Submit: 12 Solved: 4
[Submit][Status][Web Board]
Description

Bobo has a balanced parenthesis sequence P=p1 p2…pn of length n and q questions.

The i-th question is whether P remains balanced after pai and pbi 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≤105,1≤q≤105).

The second line contains n characters p1 p2…pn.

The i-th of the last q lines contains 2 integers ai,bi (1≤ai,bi≤n,ai≠bi).

Output

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

Sample Input
4 2
(())
1 3
2 3
2 1
()
1 2

Sample Output
No
Yes
No
*/

/*
题意:给一个合法括号字符串,询问调换两个字符,字符串是否仍合法? (如果括号串从左到右能镶嵌匹配就合法,其实就”合法)(合法”这
种情况不行啦),空串也合法;
思路:规律题,只有”()”这种情况需要讨论.如果询问区间内没有某个位置f(=前的左括号数减右括号数)小于2,则yes,否则no.比赛时找到规律,
却跪在线段树上了…其实可以对每个前缀区间统计f,然后前缀区间相减,如果结果大于零就no~~比赛完才立马意识到Orz…
*/

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int maxn=1e5+100;
int n,q;
int sum[maxn];
char str[maxn];

int main()
{
    while (scanf("%d%d",&n,&q)==2)
    {
        scanf("%s",str+1);
        memset(sum,0,sizeof sum);
        int num=0,now=0;//now表示当前位置f,num表示此前出现f<2的次数
        for (int i=1; i<=n; i++){
            if (str[i]=='('){
                now++;
            }
            else {
                now--;
            }
            if (now<2){
                num++;
            }
            sum[i]=num;
        }
        for (int i=1;i<=q;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            if (a>b) swap(a,b);//这应该可以坑下爹
            if (str[a]=='('&&str[b]==')'){//只需考虑();
                if(sum[a-1]==sum[b-1]){//区间前后sum值不变,说明区间内没有f<2;
                    printf("Yes\n");
                }
                else{
                    printf("No\n");
                }
            }
            else {
                printf("Yes\n");
            }
        }
    }
    return 0;
}
 类似资料:

相关阅读

相关文章

相关问答