HDU 5831 Rikca with Parthesis II(スタック&思考)


Problem Description As we know,Rika is poor at match.Yuta is worying about this situation,so he gives Rikca some match to practice.The e is one of them:
Correct parentheses sequences can be defined recursively as follows:1.The empy string“”is a corect sequence.2.If“X”and“Y”are corect sequence,then“XY”is a corect sequence.Each corect parenthesess sequence can be dervid using the above rules.Examples of corect parentheses sequences include",","()","(),"((),"(),"(),","(),",",","((),",","(),"(())),","(((.))))))),"((((.))))))
Now Yuta has a parentheses sequence S,and he wants Rikca to chose two different position i,j and swap Si,Sj.
Rikca likes corect parentheses sequence.So she wants to know ft she can change S to a corect parentheses sequence after this opation.
It is too difficult for Rikca.Can you help her?
Input The first line contains a number t(1<=t==1000)、the number of the testcases.And there re no more the n 10 testcases with n>100
For each testcase、the first line contains a n integers n(1<=n==100000)、the length of S.And the second line contains a string of length S which onlycontains'(and').
Output For each testcase,print“Yes”or“No”in a line.
Sample Input 3 4()(4()(6))))((
Sample Output Yes No
ベント
For the second sample input,Rikcan chose(1,3)or(2,4)to swap.But do nothing is not allowed.
データ構造の中かっこ合わせのレベルアップ版を練習して、列全体をかっこで合わせます.最後に残ったのはかっこだけです.
1.  

2.    ")("  "))(("
時に一回だけ交換できます.n=0に対する特判を加えて、残りは全部Noです.
注意操作が必要ですので、初期「()」の結果はNoです.
acコード:
#include 

using namespace std;

#define rep(i,a,n) for(int i = (a); i < (n); i++)
#define per(i,a,n) for(int i = (n)-1; i >= (a); i--)
#define clr(arr,val) memset(arr, val, sizeof(arr))
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define pi acos(-1)
typedef pair<int, int> pii;
typedef long long LL;
const int maxn = 1006;
const double eps = 1e-8;
const int mod = 1000000007;

int main(int argc, char const *argv[]) {
    int t;
    int n;
    string a;
    cin >> t;
    while (t--) {
        stack<char>s;
        char ans[1005];
        cin >> n;
        if(n == 0) {puts("Yes");continue;}
        cin >> a;
        int idx = 0;
        rep(i, 0, n){
            if(a[i] == '(') s.push(a[i]);
            else {
                if(!s.empty() && s.top() == '(') s.pop();
                else s.push(a[i]);
            }
        }
        bool f = false;
        if(s.empty() && n!=2) f = true;
        else {
            while (!s.empty()) {
                ans[idx++] = s.top()=='(' ? ')' :'(';
                s.pop();
            }
            ans[idx] = '\0';
            if(strlen(ans) == 2 && ans[0] ==')' && ans[1] == '(') f = true;
            if(strlen(ans) == 4 && ans[0] ==')' && ans[1] == ')' && ans[2] == '(' && ans[3] == '(') f = true;

        }
        puts(f ? "Yes" : "No");
    }
    return 0;
}