您的位置:首页 > 其它

Codevs1170 双栈排序

2015-10-29 15:05 435 查看
思路:看题解看得目瞪口呆,真的不想说什么了。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=1005;
int n,col[maxn];
int a[maxn],b[maxn];
vector<int> g[maxn];

void init()
{
scanf("%d",&n);
for (int i=1;i<=n;++i)
scanf("%d",&a[i]);
b[n+1]=1000000000;
for (int i=n;i>=1;--i)
b[i]=min(b[i+1],a[i]);
}

bool paint(int u)
{
for (int i=0;i<g[u].size();++i)
{
if (!col[g[u][i]])
{
col[g[u][i]]=3-col[u];
paint(g[u][i]);
}
else if (col[g[u][i]]==col[u])
return false;
}
return true;
}

stack<int> s[3];

int main()
{
freopen("stack.in","r",stdin);
freopen("stack.out","w",stdout);
init();
for (int i=1;i<=n;++i)
for (int j=i+1;j<=n;++j)
{
if (a[i]<a[j] && a[i]>b[j+1])
{
g[i].push_back(j);
g[j].push_back(i);
}
}
memset(col,0,sizeof(col));
for (int i=1;i<=n;++i)
if (!col[i])
{
col[i]=1;
if (!paint(i))
{
puts("0");
return 0;
}
}
int now=1;
for (int i=1;i<=n;++i)
{
if (col[i]==1)
printf("a ");
else
printf("c ");
s[col[i]].push(a[i]);
while ( (!s[1].empty() && s[1].top()==now) || (!s[2].empty() && s[2].top()==now))
{
if (!s[1].empty() && s[1].top()==now)
{
printf("b ");
s[1].pop();
}
if (!s[2].empty() && s[2].top()==now)
{
printf("d ");
s[2].pop();
}
now++;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分图判定