Problem Description
bobo found an ancient string. The string contains only three charaters – “(”, “)” and “?”.
bobo would like to replace each “?” with “(” or “)” so that the string is valid (defined as follows). Check if the way of replacement can be uniquely determined.
Note:
An empty string is valid.
If S is valid, (S) is valid.
If U,V are valid, UV is valid.
Input
The input consists of several tests. For each tests:
A string s1s2…sn (1≤n≤106).
Output
For each tests:
If there is unique valid string, print “Unique”. If there are no valid strings at all, print “None”. Otherwise, print “Many”.
Sample Input
??
???
(??
Sample Output
Unique
Many
None
贪心思想,思路借鉴:https://blog.csdn.net/The_star_is_at/article/details/69525793
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
char str[1000006];
char tmp[1000006];
bool judge(int len)
{
stack<char> st;
for(int i=0;i<len;i++){
if(tmp[i]=='('){
st.push(tmp[i]);
}
else{
if(st.empty()) return false;
st.pop();
}
}
if(!st.empty())
return false;
return true;
}
int main()
{
while(scanf("%s",&str)!=EOF)
{
int len=strlen(str);
if(len&1){
printf("None\n");
continue;
}
int l=0,r=0;
for(int i=0;i<len;i++){
if(str[i]=='(') l++;
if(str[i]==')') r++;
}
int lenl=(len-2*l)/2;//多少个问号会变成左括号
int lenr=(len-2*r)/2;//多少个问号会变成右括号
int xl=-1,xr=-1;
for(int i=0;i<len;i++){
if(str[i]=='?'){
if(lenl>0){
tmp[i]='(';
lenl--;
if(lenl==0) xl=i;
}
else{
tmp[i]=')';
if(xr==-1) xr=i;
}
}
else{
tmp[i]=str[i];
}
}
if(!judge(len))
printf("None\n");
else{
if(xl==-1||xr==-1)
printf("Unique\n");
else{
char s=tmp[xl];tmp[xl]=tmp[xr];tmp[xr]=s;
if(!judge(len))
printf("Unique\n");
else
printf("Many\n");
}
}
}
return 0;
}