hdu 5831 Rikka with Parenthesis II

来源:互联网 发布:淘宝vr眼镜 编辑:程序博客网 时间:2024/05/17 23:05

Rikka with Parenthesis II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1618    Accepted Submission(s): 711


Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

Correct parentheses sequences can be defined recursively as follows:
1.The empty string "" is a correct sequence.
2.If "X" and "Y" are correct sequences, then "XY" (the concatenation of X and Y) is a correct sequence.
3.If "X" is a correct sequence, then "(X)" is a correct sequence.
Each correct parentheses sequence can be derived using the above rules.
Examples of correct parentheses sequences include "", "()", "()()()", "(()())", and "(((())))".

Now Yuta has a parentheses sequence S, and he wants Rikka to choose two different position i,j and swap Si,Sj.

Rikka likes correct parentheses sequence. So she wants to know if she can change S to a correct parentheses sequence after this operation.

It is too difficult for Rikka. Can you help her?
 

Input
The first line contains a number t(1<=t<=1000), the number of the testcases. And there are no more then 10 testcases with n>100

For each testcase, the first line contains an integers n(1<=n<=100000), the length of S. And the second line contains a string of length S which only contains ‘(’ and ‘)’.
 

Output
For each testcase, print "Yes" or "No" in a line.
 

Sample Input
34())(4()()6)))(((
 

Sample Output
YesYesNo
Hint
For the second sample input, Rikka can choose (1,3) or (2,4) to swap. But do nothing is not allowed.
 


给出一串的括号,并且你必须进行一次随意的换括号操作,首先如果括号的数量大于2并且本身也是匹配的那就一定可以最后也是匹配的,在单独处理2个括号的情况.

然后再是一般情况,一长串的括号,至于数量是奇数或者是左右括号数量不匹配的情况就不多说了,我们队伍一开始的思路挺对的,就是从头到尾遍历,用一个计数的变量从0开始计数,

遇到左括号就加一,右括号就减一,如果没有换括号操作的情况下,只要出现了一次计数等于-1的情况,就表明括号不匹配,那么我们就想了,是不是-1出现了一次し可以用换位置操作来弥补的,于是我们就试了出现第二次-1的情况就跳出,果断wa了,后来又想了是不是所有-1的情况都可以被弥补,那么就试试-2吧,结果还是wa,然而最后试了出现-3 才跳出的情况,ac了,后来才想明白,如果2个串都出现了一次-2的情况,那么将两个串连接上,其实就只有一个-2了,因为第一个串的2个左括号会被第二个串的2个右括号匹配上,那么这个组合串也就只有一次-2出现的情况了,并且是可以被一次操作所弥补的,并且n个串连到一块也是这种情况,所以遇到-3的情况跳出才是正解....


#include<iostream>#include<cstring>using namespace std;int main(){char a[111111];int T;cin>>T;while(T--){int l;cin>>l;cin>>a;int i;int js=0;int flag=1;int js1=0;int js2=0;if(l%2==1){cout<<"No"<<endl;continue;}     for(i=0;i<l;i++)    {    if(a[i]=='(')js1++;    if(a[i]==')')js2++;}if(js1!=js2){cout<<"No"<<endl;continue;}if(l==2){if(a[0]=='('&&a[1]==')'){cout<<"No"<<endl;continue;}    else {    cout<<"Yes"<<endl;    continue;}}for(i=0;i<l;i++){if(a[i]=='(')js++;if(a[i]==')')js--;if(js==-3){flag=0;break;}}if(flag)cout<<"Yes"<<endl;else cout<<"No"<<endl; }return 0;} 


原创粉丝点击