C. Recover an RBS
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example:
- bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");
- bracket sequences ")(", "(" and ")" are not.
There was an RBS. Some brackets have been replaced with question marks. Is it true that there is a unique way to replace question marks with brackets, so that the resulting sequence is an RBS?
Input
The first line contains a single integer tt (1≤t≤5⋅1041≤t≤5⋅104) — the number of testcases.
The only line of each testcase contains an RBS with some brackets replaced with question marks. Each character is either '(', ')' or '?'. At least one RBS can be recovered from the given sequence.
The total length of the sequences over all testcases doesn't exceed 2⋅1052⋅105.
Output
For each testcase, print "YES" if the way to replace question marks with brackets, so that the resulting sequence is an RBS, is unique. If there is more than one way, then print "NO".
Example
input
Copy
5
(?))
??????
()
??
?(?)()?)
output
Copy
YES NO YES YES NO
Note
In the first testcase, the only possible original RBS is "(())".
In the second testcase, there are multiple ways to recover an RBS.
In the third and the fourth testcases, the only possible original RBS is "()".
In the fifth testcase, the original RBS can be either "((()()))" or "(())()()".
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
stack<char> stk;
string s;
cin>>s;
int l=0,r=0; //左括号与右括号的数量统计
int q=0; //"?"的数量
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
{
l++;
}
else if(s[i]==')')
{
r++;
}
else if(s[i]=='?')
{
q++;
}
}
int c; //求成对的的括号个数,也代表单个左括号和右括号的个数
int dis1,dis2;
if(r>=l) //如果右括号比左括号多
{
dis1=(q-(r-l))/2;
c=r+dis1;
}
else if(l>r)
{
dis2=(q-(l-r))/2;
c=l+dis2;
}
if((dis1==0&&r>=l)||(dis2==0&&l>r)||s.size()==2) //说明把问号全部用来填补左括号,或者全部用来填补右括号,是唯一的
{
puts("YES");
continue;
}
//现在把"?"填起来
int li=c-l,ri=c-r; //分别表示"?"处有多少左括号和右括号
bool flag=false;
for(int i=0;i<s.size();i++)
{
if(s[i]=='?')
{
if(flag&&li==1)
{
s[i]='(';
li--;
continue;
}
if(li>1)
{
s[i]='(';
li--;
}
else if(li==1)
{
s[i]=')';
flag=true;
}
else if(li==0){
s[i]=')';
}
}
}
//现在检验一下把括号序列的"?"填满后的括号序列是否匹配
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
{
stk.push(s[i]);
}
else if(s[i]==')')
{
if(stk.size())
stk.pop();
}
}
// cout<<"333333"<<endl;
if(stk.empty())
{
puts("NO"); //有次优解
}
else puts("YES");
}
return 0;
}