Portal
Key idea: Seeing this kind of bracket matching problem, one is thinking of stacking, and the other is thinking of seeing the left parenthesis as + 1 +1+ 1 , think of it as− 1 -1 afterseeing the right parenthesis− 1 , from left to right, we judge whether the sum of the prefix on each digit is>= 0 >=0>=0 , and the prefix sum of the last digit= 0 =0=0
Solution: Because there is only one left and right parenthesis in the given characters, the total length of the characters is∣ s ∣ |s|∣ s ∣ , then∣ s ∣ − 2 |s|-2∣s∣−Replace with 2 question marks, because this string must match at the end, that is to say, for example, the opening parenthesis is+ 1 +1+ 1 , the right parenthesis is− 1 -1− 1 , then it is inevitable that each person cannot be negative. A negative value means that there are too many closing brackets. So one way is to change the front∣ s ∣ / 2 − 1 |s|/2-1∣s∣/2−1 question mark for the left parenthesis replace all the remaining question marks replace all right parenthesis, especially the last sentence it again.
rush(){
cin>>ori;
int len=ori.size(),cnt=len/2-1;
rep(i,0,len-1)ori[i]=(ori[i]!='?')?ori[i]:((cnt--)>0?'(':')');
int tmp=0;
bool flag=true;
rep(i,0,len-1){
tmp+=ori[i]=='('?1:-1;
if(tmp<0)flag=false;
}
if(tmp!=0)flag=false;
printf("%s\n",flag?"YES":"NO");
}
Talking about my approach, I just glanced blindly at the beginning. I didn’t notice that there is only one left parenthesis and one right parenthesis in the question. I thought there were many left parentheses, right parentheses and question marks. I took a look at the data range ∣ s ∣ <100 |s|<100∣s∣<1 0 0 , the idea is still+ 1, − 1 +1, -1+1,−1 That kind of method, so when it comes to the question mark, you need to choose whether to make a left parenthesis or a right parenthesis. If all the left parentheses are used, it will be100 100 in the end.1 0 0 , which means that the value that can be taken on each bit is200 200Within 2 0 0 , then the loop array processing down to what values can be taken on each bit, see the left parenthesis+ 1 +1+ 1 , see the right parenthesis− 1 -1− 1 , when you see the question mark, deal with it separately+ 1 +1+ 1 and− 1 -1− 1 , the final special judgment is sufficient
string s;
const int N=1e2+5;
int tmp[2][205];
int main(){
#ifdef io
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
rush(){
cin>>s;
int len=s.size();
bool flag=true;
rep(i,-100,100)tmp[0][i+100]=tmp[1][i+100]=0;
tmp[0][100]=1;
rep(i,1,len){
int now=i%2,up=(i-1)%2;
rep(j,-100,100)tmp[now][j+100]=0;
if(s[i-1]=='('){
rep(j,0,100){
if(tmp[up][j+100])tmp[now][j+1+100]=1;
}
}else if(s[i-1]==')'){
int ff=0;
rep(j,1,100){
if(tmp[up][j+100])tmp[now][j-1+100]=1,ff=1;
}
if(!ff){
flag=false;
break;
}
}else{
rep(j,-1,100)if(tmp[up][j+100])tmp[now][j+1+100]=1;
rep(j,1,100)if(tmp[up][j+100])tmp[now][j-1+100]=1;
}
}
if(!tmp[len%2][100])flag=false;
printf("%s\n",(flag?"YES":"NO"));
}
return 0;
}