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

hdu 4915 Parenthese sequence(多校第5场,括号匹配,贪心算法)

2014-08-07 11:25 483 查看
题目大意:

看上一篇。题目一样,解法不同。

思路:

YY构造,正确性不会证明。

网上有很多关于该题的YY做法,但是正确性不会证明T^T。

扫一遍字符串,把必须变掉的?先变掉。最后如果有?多出来,试着把最中间的?分别变成( 和 )。比赛的时候这一步没有写T^Twa到死。。。。

用栈保存了( 用队列保存了? T^T主要是不会双向队列,悲伤。。当碰到 )时,如果栈中有值,那么删掉栈顶,否则,如果队列有值,队头出列,否则就是不能匹配。因为,越左边的( 可以选择的余地越大,越边上的?可以选择的余地越小。所以尽可能的把有用的保存下来,去掉相对没有用的。最后剩下的栈和队列分别保存了没有匹配掉的(和?。把他们两个进行匹配。

具体看代码:

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
queue<int>q;
stack<int>s,sq;
int len;
char str[1111111];
bool check(int x)
{
bool flag = true;
while(!q.empty())q.pop();
while(!s.empty())s.pop();
int i,j;
for(i=0; i<len; i++)
{
if(str[i]=='(')s.push(i);
else if(str[i]=='?')
{
q.push(i);
}
else
{
if(s.empty()&&q.empty())
{
flag=false;
break;
}
else if(!s.empty())s.pop();
else if(!q.empty())
{
int tem =q.front();
if(x==1)
{
str[tem]='(';
q.pop();
}
}
}
}
if(!flag)
{
return false;
}
while(!sq.empty())sq.pop();
while(!q.empty())
{
int tem = q.front();
sq.push(tem);
q.pop();
}
while(!s.empty()&&!sq.empty())
{
int left=s.top();
int quest=sq.top();
if(left>=quest)break;
if(x==1)
str[quest]=')';
s.pop();
sq.pop();
}
if(!s.empty())
{
return false;
}
return true;
}
int main()
{
int i,j;
while(scanf("%s",str)!=-1)
{
len = strlen(str);
if(len&1 || str[0]==')' || str[len-1]=='(')
{
printf("None\n");
continue;
}

str[0]='(';
str[len-1]=')';
if(check(1)==false)printf("None\n");
else if(sq.empty())
{
printf("Unique\n");
}
else
{
int count=0;
int temcount=0;
for(i=0; i<len; i++)
if(str[i]=='?')count++;
count /= 2;
for(i=0; i<len; i++)
if(str[i]=='?')
{
temcount++;
if(temcount==count)break;
}
int index=i;

str[index]='(';
bool x1 = check(0);
str[index]=')';
bool x2 = check(0);
if(x1&&x2)printf("Many\n");
else if((x1&&!x2)||(!x1&&x2))printf("Unique\n");
else printf("None\n");

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