您的位置:首页 > 产品设计 > UI/UE

HDU 4915 Parenthese sequence

2014-08-07 11:00 309 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4915

解题报告:从前往后遍历一次,每次判断')'的数目是不是满足 n < (i +1)/ 2,从后往前遍历一次,每次判断'('的数目是不是满足 n <= (len - i) / 2;

这样就可以判断出这个序列是否存在匹配的序列。接下来就是判断是Many还是Unique的情况,因为数据是10的六次方,所以遇到问号改成'(' 或')'暴力判断是不行的,但是我们可以判断出只要(和)的数目小于等于len / 2而且有三个连续的?那句是Many,否则再进行暴力判断,这样就可以大大减小时间复杂度。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1000000+5;
char str[maxn];

int judge(char* str)
{
int len = strlen(str);
int a = 0,b = 0;
for(int i = 0,j = len- 1;i < len,j >= 0;++i,--j)
{
if(str[i] == ')') a++;
if(str[j] == '(') b++;
if(a >  (i + 1) / 2) return 0;
if(b > (len - j) / 2) return 0;
}
return 1;
}
int main()
{
//    freopen("1005.in","r",stdin);
int T = 0;
while(scanf("%s",str)!=EOF)
{
T++;
int ans;
ans = judge(str);
int l = strlen(str);
if(l & 1) ans = 0;
if(!ans)
{
puts("None");
continue;
}
int len =  strlen(str);
int a = 0,b = 0,c = 0,f = 0,M = 0;
for(int i = 0;i < len;++i)
{
if(str[i] == '(') a++;
if(str[i] == ')') b++;
if(str[i] == '?')
{
f++;
c++;
}
else
{
M = max(M,f);
f = 0;
}
}
if(a >= len / 2 || b >= len / 2 || c <= 1)
{
puts("Unique");
continue;
}
if(M >= 3)
{
puts("Many");
continue;
}
ans = 0;
for(int i = 0;i < len;++i)
if(str[i] == '?')
{
int tt = 0;
str[i] = '(';
tt += judge(str);
str[i] = ')';
tt += judge(str);
if(tt == 2)
{
ans = 1;
break;
}
str[i] = '?';
}
printf(ans? "Many\n":"Unique\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: