bzoj 4010: [HNOI2015]菜肴制作【拓扑排序】

也就是给定有向图,求最小字典序的拓扑序,直接用小根堆就行(或者反着建图用大根堆)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=100005;
int T,n,m,d[N],h[N],cnt,ans[N];
priority_queue<int>q;
struct qwe
{
    int ne,to;
}e[N<<1];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
void add(int u,int v)
{
    cnt++;
    e[cnt].ne=h[u];
    e[cnt].to=v;
    h[u]=cnt;
    d[v]++;
}
int main()
{
    T=read();
    while(T--)
    {
        memset(h,0,sizeof(h));
        memset(d,0,sizeof(d));
        cnt=0;
        n=read(),m=read();
        for(int i=1;i<=m;i++)
        {
            int x=read(),y=read();
            add(y,x);
        }
        int now=0;
        for(int i=1;i<=n;i++)
            if(!d[i])
                q.push(i);
        while(!q.empty())
        {
            int u=q.top();
            q.pop();
            ans[++now]=u;
            for(int i=h[u];i;i=e[i].ne)
                if(!(--d[e[i].to]))
                    q.push(e[i].to);
        }
        if(now==n)
        {
            for(int i=n;i>=1;i--)
                printf("%d ",ans[i]);
            puts("");
        }
        else
            puts("Impossible!");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/9697673.html
今日推荐