2016湖南省赛----G

2016湖南省赛----G - Parenthesis (括号匹配)
 
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 3
2 3
2 1
()
1 2

Sample Output

No
Yes
No

題意: 给出一个已经匹配的括号序列,任意的交换两个位置的括号,判断是否匹配,如果匹配输出 Yes 不匹配输出 No。

输入一个n一个m,n表示括号序列的长度,m代表下面给出m种交换方式,对每一种方式进行判断。

思路:

  可将该问题分为三类:

            1. 若交换的两个位置的括号相同 则可直接输出 Yes;

            2.若后面的左括号与前面的右括号交换,则可直接输出Yes. 因为一开始是平衡串,  如果左边的字符')'与右边的'('交换,那么此时交换的两个必能匹配为一对。

            3.若后面的右括号与前面的左括号交换,则可根据括号匹配问题进行判断.

代码实现:

#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <stdio.h>
#include <stack>
using namespace std;


char s1[300000]={0};


int main(){
    int n,m;
    while(~scanf("%d%d",&n,&m)){
            getchar();
            scanf("%s",s1);
            int a,b;
            for(int i=1;i<=m;i++){
                char c;
                scanf("%d%d",&a,&b);
                if(a>b)
                    swap(a,b);
                if(s1[a-1]==s1[b-1]||s1[b-1]=='('){                   //第一种情况与第二种情况
                  printf("Yes
");
                  continue;
                }
                swap(s1[a-1],s1[b-1]);
                int sum = 0;
                for(int i = 0;i<n;i++){                                          //  第三种情况的判断
                    if(s1[i]=='(')
                        sum++;
                    if(s1[i]==')')
                        sum--;
                    if(sum<0)
                        break;
                }
                if(sum==0)
                    printf("Yes
");
                else
                    printf("No
");
                swap(s1[a-1],s1[b-1]);                                    //将字符串还原
            }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/LGJC1314/p/6714934.html