Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1559 Accepted Submission(s): 625
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.
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 s 1s 2…s n (1≤n≤10 6).
A string s 1s 2…s n (1≤n≤10 6).
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".
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
Author
Xiaoxu Guo (ftiasch)
Source
Recommend
先处理出问号数,左括号数,右括号数,问号就是先补齐左右括号的差值,剩下的再平均分.
知道了要补几个左括号几个右括号之后,先把左括号放到最左边的问号位置,右括号放到最右边的问号位置.
扫一遍如果合理,至少有一解.
把最后一个用左括号替换的问号和第一个用右括号替换的问号交换,若合理,则多解.
#include<iostream>
#include<string>
#include<set>
#include <stack>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAXN=1000000+10;
string s;
string t;
stack<int> a;
int pre[MAXN];
int len;
int check(){
int n=len;
int num=0;
for(int i=0;i<n;i++){
if(t[i]=='(')
num++;
else{
num--;
if(num<0)
return 0;
}
}
if(num>0)
return 0;
return 1;
}
int main(){
// freopen("data.txt","r",stdin);
// freopen("f.txt","w",stdout);
t.resize(MAXN);
while(cin>>s){
len=s.length();
int s1=0,s2=0;
if(len&1){
puts("None");
continue;
}
int x=0,y=0,z=0;
for(int i=0;i<len;i++){
if(s[i]=='(')
x++;
else if(s[i]==')')
y++;
else
z++;
}
if(x-y>z||y-x>z){
puts("None");
continue;
}
int xx=(z-x+y)/2;
int yy=(z+x-y)/2;
for(int i=0;i<len;i++){
if(s[i]=='?'){
if(s1<xx){
t[i]='(';
s1++;
}
else
t[i]=')';
}
else
t[i]=s[i];
}
int num=0;
if(!check()){
puts("None");
continue;
}
if(xx==z||yy==z){
puts("Unique");
continue;
}
int ok=0;
int ans=0;
for(int i=0;i<len;i++){
if(s[i]=='?'&&ok==xx){
swap(t[i],t[ans]);
break;
}
if(s[i]=='?'&&ok==xx-1){
ok++;
ans=i;
}else if(s[i]=='?'){
ok++;
}
}
if(check()){
puts("Many");
}else{
puts("Unique");
}
}
}

本文介绍了一个关于括号序列的有效性和唯一性判断问题。通过替换字符串中的问号为括号,来确保生成的字符串是一个有效的括号序列,并探讨了是否只有一种有效的方法来完成这种替换。

被折叠的 条评论
为什么被折叠?



