题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4915
Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 172 Accepted Submission(s): 69
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
这道题目,比赛的时候和队友讨论了一下,觉得搜索TLE的可能性巨大,于是果断采取了其他的方法。
我们的方法其实就是扫了二遍。中复杂度接近O(N).
用cnt来统计‘(’的数量,接着模拟一个链表来存储可能发生变化的'?'.
head表示链表头。遇到')'时若cnt>0,即前面还有'('剩余时,则让cnt--,即相互抵消掉,若cnt==0,,则取
出链表中的一个元素,把它改成'(',即让cnt++。到最后如果cnt还有剩,则显然是不可能的,但要判断是"Unique"
还是"Many",则需要把表头所表示的元素改成'(',若还是符合则是"Many" 否则是"Unique".
详见程序啦。。。
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<map>
#include<set>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<bitset>
using namespace std;
#define CLR(A) memset(A,-1,sizeof(A))
typedef long long ll;
const int MAX=1000010;
char str[MAX];
int next[MAX],head=-1,cnt,tail=0;
int solve(){
head=-1;cnt=0;tail=0;
CLR(next);
for(int i=0;str[i];i++){
if(str[i]=='(') cnt++;
else if(str[i]==')'){
if(cnt==0){
if(head==-1) return 0;
cnt++;
head=next[head];
}
else cnt--;
}
else{
if(cnt>0){
cnt--;
next[tail]=i;
tail=i;
if(head==-1) head=i;
}
else{
cnt++;
}
}
}
if(cnt!=0) return 0;
else return 1;
}
int main(){
while(~scanf("%s",str)){
int len=strlen(str);
bool ret=1;
if(len&1){
printf("None\n");continue;
}
ret=solve();
if(ret==0){
printf("None\n");continue;
}
if(head==-1){
printf("Unique\n");continue;
}
str[head]='(';
ret=solve();
if(ret==0) printf("Unique\n");
else printf("Many\n");
}
return 0;
}