Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 85 Accepted Submission(s): 28
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.
A string s1s2…sn (1≤n≤106).
If there is unique valid string, print "Unique". If there are no valid strings at all, print "None". Otherwise, print "Many".
題意:給你一串帶有‘(’,‘)’和‘?’的字符串,‘?’可以變爲任意括號,判斷該串是否符合條件。若符合,判斷是否唯一。
思路:先把特殊情況排除掉:長度爲奇數,任意一種括號大於一半。然後這麼搞:
令一半長度爲half,左括號數爲lsum,則將前 half - lsum 個‘?’變爲‘(’,剩餘的變爲‘)’。這是極端情況,若這樣也不符合,那就一定找不到符合的。若符合,則將最後一個左括號與第一個右括號(都是由‘?’變過去的,若其中一個沒有,則解唯一)調換,若這也符合條件,說明解不唯一;否則解唯一
代碼:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <functional>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
//#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
#define INF 1e9
#define MAXN 21
const int maxn = 1000005;
//#define mod 1000000007
#define eps 1e-7
#define pi 3.1415926535897932384626433
#define rep(i,n) for(int i=0;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define scan(n) scanf("%d",&n)
#define scanll(n) scanf("%I64d",&n)
#define scan2(n,m) scanf("%d%d",&n,&m)
#define scans(s) scanf("%s",s);
#define ini(a) memset(a,0,sizeof(a))
#define out(n) printf("%d\n",n)
//ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b);}
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
char s[maxn];
bool check()
{
int f = 0;
int len = strlen(s);
rep(i,len)
{
if(s[i] == '(') f ++;
else f--;
if(f < 0) return false;
}
if(f != 0) return false;
return true;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#endif
while(~scanf("%s",s))
{
int len = strlen(s);
if(len & 1)
{
puts("None");
continue;
}
int half = len / 2;
int lsum = 0,rsum = 0;
bool ok = 1;
rep(i,len)
{
if(s[i] == '(') lsum ++;
if(s[i] == ')') rsum ++;
}
if(lsum > half || rsum > half)
{
puts("None");
continue;
}
int rest = half - lsum;
int lastLeft = -1,firstRight = -1;
rep(i,len)
{
if(s[i] == '?')
{
if(rest > 0)
{
rest --;
s[i] = '(';
if(rest == 0) lastLeft = i;
}
else
{
s[i] = ')';
if(firstRight == -1) firstRight = i;
}
}
}
if(!check()) puts("None");
else
{
if(lastLeft == -1 || firstRight == -1)
{
puts("Unique");
continue;
}
swap(s[lastLeft],s[firstRight]);
if(check()) puts("Many");
else puts("Unique");
}
}
return 0;
}