Rikka with Parenthesis II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 603 Accepted Submission(s): 344
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?
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 ‘)’.
3 4 ())( 4 ()() 6 )))(((
Yes Yes NoHintFor the second sample input, Rikka can choose (1,3) or (2,4) to swap. But do nothing is not allowed.
以下附上代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#define max(a,b) (a>b?a:b)
using namespace std;
char a[100009];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,i;
scanf("%d",&n);
getchar();
scanf("%s",a);
int k=0;
if(strcmp(a,"()")==0)
{
printf("No\n");
}
else
{
for(i=0; i<n; i++)
{
if(a[i]=='(')
{
k++;
}
if(a[i]==')')
{
k--;
}
if(k<-2)
{
break;
}
}
if(k==0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}