BZOJ4010: [HNOI2015]菜肴制作

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=4010

求反图的拓扑排序并逆序输出之。用个priority_queue就可以了。

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#define rep(i,l,r) for (int i=l;i<=r;i++)
#define down(i,l,r) for (int i=l;i>=r;i--)
#define clr(x,y) memset(x,y,sizeof(x))
#define ll long long
#define maxn 200005
#define mm int(1e9+7)
using namespace std;
struct data{int obj,pre;
}e[maxn];
priority_queue<int >q;
int head[maxn],d[maxn],ans[maxn];
int n,cnt,tot,t,m;

void insert(int x,int y){
    e[++tot].obj=y; e[tot].pre=head[x]; head[x]=tot; 
}
ll read(){
    ll x=0,f=1; char ch=getchar();
    while (!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
    while (isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
void solve(int u){
    q.pop();
    ans[++cnt]=u;
    for (int j=head[u];j;j=e[j].pre){
        int v=e[j].obj;
        d[v]--;
        if (!d[v]) q.push(v);
    }
}
int main(){
    t=read();
    while (t--){
        tot=cnt=0; clr(head,0); clr(d,0);
        n=read(); m=read();
        rep(i,1,m) {
            int x,y;
            x=read(); y=read();
            insert(y,x); d[x]++;
        }
        rep(i,1,n) if (!d[i]) q.push(i);
        while (!q.empty()) solve(q.top());
        if (cnt!=n) puts("Impossible!");
        else {
            for(int i=n;i;i--)
                printf("%d ",ans[i],i==1?'\n':' ');
            puts("");
        }    
    }
    return 0;
}

 

posted on 2015-11-24 14:11  ctlchild  阅读(163)  评论(0编辑  收藏  举报

导航