ACM 杂题 hdu4915 Parenthese sequence
锻炼问题的一步步分析能力,考察选手细致。
Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 0 Accepted Submission(s): 0
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 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".
Sample Input
?? ???? (??
Sample Output
Unique Many None
Accepted | 4915 | 62MS | 1320K |
/*
* Author: NICK WONG
* Created Time: 8/5/2014 16:08:26
* File Name: 1005.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
#define out(x) cout<<#x<<": "<<x<<endl
const double eps(1e-8);
const int maxn=1010000;
const long long maxint=-1u>>1;
const long long maxlong=maxint*maxint;
typedef long long lint;
char s[maxn];
int x,y,z,ll,rr,len;
void init()
{
}
int work()
{
x=y=z=0;
len=strlen(s)-1;
if (len%2==1 || s[1]==')' || s[len]=='(') return -1;
s[1]='('; s[len]=')';
s[len+1]='(';
for (int i=1; i<=len; i++)
{
if (s[i]=='(') x++; else
if (s[i]=='?')
{
if (x==0 && z==0) x++; else
z++;
} else
if (s[i]==')')
{
if (x>=1) x--; else z--;
if (z<0) return -1;
if (x==0 && z==1) { x=1; z=0; }
//if (x+z==0 && s[i+1]=='?') s[i+1]='(';
}
}
ll=z-x;
if (ll<0) return ll;
x=y=z=0;
for (int i=len; i>=1; i--)
if (s[i]==')') y++; else
if (s[i]=='?') z++; else
if (s[i]=='(')
{
if (y>=1) y--; else z--;
if (z<0) return -1;
}
rr=z-y;
if (rr<0) return rr;
return ll;
}
int main()
{
while(scanf("%s",s+1)!=EOF)
{
s[0]=')';
init();
int tmp=work();
if (tmp<0) cout<<"None"<<endl; else
if (tmp==0) cout<<"Unique"<<endl; else
cout<<"Many"<<endl;
}
return 0;
}