AC日记——双栈排序 洛谷 P1155

双栈排序

思路:

  二分图染+模拟;

代码:

#include <bits/stdc++.h>
using namespace std;
#define maxn 1005
#define maxm 2000005
int n,head[maxn],E[maxm],V[maxm],cnt,col[maxn];
int minn[maxn],ai[maxn],sta1[maxn],sta2[maxn],top1,top2;
bool if_[maxn][maxn];
inline void in(int &now)
{
    char Cget=getchar();now=0;
    while(Cget>'9'||Cget<'0')Cget=getchar();
    while(Cget>='0'&&Cget<='9')
    {
        now=now*10+Cget-'0';
        Cget=getchar();
    }
}
void edge_add(int u,int v)
{
    E[++cnt]=head[u],V[cnt]=v,head[u]=cnt;
    E[++cnt]=head[v],V[cnt]=u,head[v]=cnt;
}
bool dfs(int now,int dis,int fa)
{
    if(col[now]) return true;
    col[now]=dis+1;
    for(int i=head[now];i;i=E[i])
    {
        if(V[i]==fa) continue;
        if(dfs(V[i],dis^1,now)) return true;
    }
    return false;
}
int main()
{
    in(n);
    for(int i=1;i<=n;i++) in(ai[i]);
    minn[n]=ai[n];
    for(int i=n-1;i>=1;i--) minn[i]=min(minn[i+1],ai[i]);
    for(int i=1;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            if(minn[j+1]<ai[i]&&ai[i]<ai[j])
            {
                if(!if_[i][j])
                {
                    if_[i][j]=true;
                    if_[j][i]=true;
                    edge_add(i,j);
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(!col[i])
        {
            if(dfs(i,0,0))
            {
                printf("0");
                return 0;
            }
        }
    }
    int now=1;
    for(int i=1;i<=n;i++)
    {
        if(ai[i]>now)
        {
            if(col[i]==1) putchar('a'),sta1[++top1]=ai[i];
            else putchar('c'),sta2[++top2]=ai[i];
        }
        else
        {
            now++;
            if(col[i]==1) printf("a b");
            else printf("c d");
            while(1)
            {
                if(sta1[top1]==now) 
                {
                    printf(" b"),top1--;
                    now++;continue;
                }
                if(sta2[top2]==now) 
                {
                    printf(" d"),top2--;
                    now++;continue;
                }
                break;
            }
        }
        if(i!=n) putchar(' ');
    }
    while(top1--) printf(" b");
    while(top2--) printf(" d");
    return 0;
}
原文地址:https://www.cnblogs.com/IUUUUUUUskyyy/p/6973923.html