【bzoj4010】 HNOI2015—菜餚製作

http://hzwer.com/6820.html (題目鏈接)

題意:給出一張無向圖要求出一個拓撲序列滿足1的位置最靠前 ,在保證上面的條件下使2的位置最靠前 ,在保證上面的條件下使3的位置最靠前 ……

Solution
  構造逆拓撲序,套個堆每次選出編號最大的加入答案,輸出答案時從後往前輸出。
  有點難想,但是腦補一下還是OK的。

代碼:

// bzoj4010
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<queue>
#define MOD 1000000007
#define inf 2147483640
#define LL long long
#define free(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout);
using namespace std;

const int maxn=100010;
struct edge {int to,next;}e[maxn<<1];
priority_queue<int> q;
int head[maxn],ans[maxn],d[maxn],n,m,top,cnt;

void link(int u,int v) {
    e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;
}
int main() {
    int T;scanf("%d",&T);
    while (T--) {
        scanf("%d%d",&n,&m);cnt=0;
        memset(head,0,sizeof(head));memset(d,0,sizeof(d));
        for (int u,v,i=1;i<=m;i++) {
            scanf("%d%d",&u,&v);
            link(v,u);d[u]++;
        }
        top=0;
        while (q.size()) q.pop();
        for (int i=1;i<=n;i++) if (!d[i]) q.push(i);
        while (q.size()) {
            int x=q.top();q.pop();
            ans[++top]=x;
            for (int i=head[x];i;i=e[i].next) {
                d[e[i].to]--;
                if (d[e[i].to]==0)
                    q.push(e[i].to);
            }
        }
        if (top!=n) printf("Impossible!\n");
        else {
            for (int i=n;i>=1;i--) printf("%d ",ans[i]);
            printf("\n");
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章