Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 297 Accepted Submission(s): 126
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
Author
Xiaoxu Guo (ftiasch)
Source
2014 Multi-University Training Contest 5
题意:给出一串字符串,在问号处加左括号或右括号,是的这串的字符的括号全部匹配。
看了网上一位大牛的题解才做出来的。
首先字符串是奇数个肯定匹配不了,然后从左往右扫一片用两个数组分别记录左括号的最大和最小的个数(出现?号最小的那个减,当做这个位置是‘)’匹配了,最大的加),如果出现最小的比最大的还大,说明右括号已经多余左括号了,肯定不行,然后同理从右往左扫一遍,记录右括号的最大最小个数。
最后再从右往左扫一遍,找每个位置两个最小值里的最小值,两个最大里面的最大比较,如果最小比最大大,不行,如果都相等就只有一种情况,否则有多重情况。
因为取最小的两个值分别是从左往右和从右往左记录的最小的未匹配的右括号和左括号的个数,两个最大值是尽量多的将?号变成左括号或右括号的个数,所以只要两个最大值里的大的比两个最小值里小的大,就会有多重情况(?号可以变成左右括号),相等当然就只有一种情况。
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXN=1000010;
int a[MAXN][2],b[MAXN][2];
char s[MAXN];
int main()
{
int i,n,flag;
while(scanf("%s",s+1)!=EOF)
{
n=strlen(s+1);
if(n%2!=0)
{
printf("None\n");
continue;
}
a[0][1]=a[0][0]=b[n][0]=b[n][1]=0;
flag=0;
for(i=1;i<=n;i++)
{
if(s[i]=='(')
{
a[i][0]=a[i-1][0]+1;
a[i][1]=a[i-1][1]+1;
}
else if(s[i]==')')
{
if(a[i-1][0]==0)
a[i][0]=1;
else a[i][0]=a[i-1][0]-1;
a[i][1]=a[i-1][1]-1;
}
else if(s[i]=='?')
{
if(a[i-1][0]==0)
a[i][0]=1;
else
a[i][0]=a[i-1][0]-1;
a[i][1]=a[i-1][1]+1;
}
if(a[i][0]>a[i][1])
{
flag=1;
break;
}
}
if(flag)
{
printf("None\n");
continue;
}
for(i=n;i>=1;i--)
{
if(s[i]==')')
{
b[i-1][0]=b[i][0]+1;
b[i-1][1]=b[i][1]+1;
}
else if(s[i]=='(')
{
if(b[i][0]==0)
b[i-1][0]=1;
else b[i-1][0]=b[i][0]-1;
b[i-1][1]=b[i][1]-1;
}
else if(s[i]=='?')
{
if(b[i][0]==0)
b[i-1][0]=1;
else
b[i-1][0]=b[i][0]-1;
b[i-1][1]=b[i][1]+1;
}
if(b[i][0]>b[i][1])
{
flag=1;
break;
}
}
if(flag)
{
printf("None\n");
continue;
}
for(i=1;i<=n;i++)
{
int ta=max(a[i][0],b[i][0]);
int tb=min(a[i][1],b[i][1]);
if(ta>tb)
{
flag|=1;
break;
}
if(ta<tb)
{
flag|=2;
break;
}
}
if(flag==1)
{
printf("None\n");
}
else if(flag==2)
{
printf("Many\n");
}
else
printf("Unique\n");
}
}