1. 程式人生 > 實用技巧 >Regular Bracket Sequence

Regular Bracket Sequence

A. Regular Bracket Sequence

A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".

You are given a sequence s of n characters "(", ")", and/or "?". There is exactly one character ( and exactly one character ) in this sequence.

You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced

.

Determine if it is possible to obtain an "RBS" after these replacements.

Input

The first line contains one integer t \((1\leq t\leq 1000)\) — the number of test cases.

Each test case consists of one line containing s \((2\leq |s|\leq 100)\) a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character )

in this sequence.

Output

For each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise.

You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

Example

input

Copy

5
()
(?)
(??)
??()
)?(?

output

Copy

YES
NO
YES
YES
NO

Note

In the first test case, the sequence is already an RBS.

In the third test case, you can obtain an RBS as follows: ()() or (()).

In the fourth test case, you can obtain an RBS as follows: ()().

沒有引號,看不懂加粗字型,原來是隻有一個左括號和一個右括號

考慮字首和,左括號+1,右括號-1,則除了?,一個合法的序列是字首和均大於零且sum[n]=0

考慮把?替換成1或-1,因為1和-1的個數是確定的,通過sum[n]可求出來

考慮貪心,先讓所有1放左邊,-1接著放-1,這樣就能讓字首和儘可能多的大於等於0

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN=108,mod=1e9+7,inf=0x3f3f3f3f;
char s[1000];
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",s);
        int n=strlen(s),ans=1;
        int a=0,b=0,c=0;
        for(int i=0;i<n;++i){
            if(s[i]=='(')a++;
            if(s[i]=='?')b++;
            if(s[i]==')')c++;
        }
        if((a-c+b)&1)ans=0;
        int x=(a-c+b)/2,y=b-x;
        if(y<0)ans=0;
        if(x<0)ans=0;
        for(int i=0;i<n;++i){
            if(s[i]=='?'){
                if(x)s[i]='(',x--;
                else s[i]=')',y--;
            }
        }
        for(int i=0,tot=0;i<n;++i){
            if(s[i]=='(')tot++;
            if(s[i]==')')tot--;
            if(tot<0)ans=0;
        }
        if(ans)puts("YES");
        else puts("NO");
    }
    return 0;
}