您的位置:首页 > 编程语言 > C语言/C++

2016多校8 hdu5831 Rikka with Parenthesis II 水题

2016-08-13 00:22 411 查看


Rikka with Parenthesis II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 2571    Accepted Submission(s): 913


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

3
4
())(
4
()()
6
)))(((

 

Sample Output

Yes
Yes
No

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

给你一个只包含左括号或右括号的串,要求你随机交换其中两个括号的位置一次,然后求得到的串是否合法

比如像)))(((这样的串我们是怎样也挽救不回来了,但是))((这样的括号可以交换首末两个位置变成()(),这样就是合法串

想象有任意合法串,我们用A,B,C,D,E来表示

那么能挽救回来的串的最糟糕形势无非就是 A ) B ) C ( D ( E

其中用字母表示的地方前后括号都是能匹配的。那么最先先统计左括号和右括号的个数,如果不想等直接判no

用一个ans=0,遇到左括号的时候ans++,遇到右括号的时候ans--

那么当ans<-2时,输入的串已经超出了我们的控制范围。。。

还有点,就是每个串必须交换一次位置,所以()这样的输入也是no

下面贴代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=100000;
char save[maxn+5];
//int panduan[maxn+5];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
if(n==1){
scanf("%s",save);
printf("No\n");
continue;
}
scanf("%s",save);
int i,j,k;
int before=0,after=0;
for(i=0;i<n;i++){
if(save[i]=='('){
before++;
}else{
after++;
}
}
if(before!=after){
printf("No\n");
continue;
}
int ans=0;
bool flag=false;
for(i=0;i<n;i++){
if(save[i]=='('){
ans++;
}else{
ans--;
}
if(ans<-2){
flag=true;
break;
}
}
if(n==2&&save[0]=='('&&save[1]==')'){
printf("No\n");
continue;
}
if(flag){
printf("No\n");
continue;
}else{
printf("Yes\n");
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息