BestCoder #1-1 HDU 4857 逆拓撲排序

//
//  main.cpp
//  HDU 4857 拓撲排序
//
//  Created by 鄭喆君 on 8/9/14.
//  Copyright (c) 2014 itcast. All rights reserved.
//

#include<cstdio>
#include<cstring>
#include<iostream>
#include<iomanip>
#include<queue>
#include<cmath>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int int_max = 0x07777777;
const int int_min = 0x80000000;
const int maxn = 31000;
struct cmp {
    bool operator()(int a, int b){
        return a < b;
    }
};
vector<int> g[maxn];
int cnt[maxn];
int n,m;
int main(int argc, const char * argv[])
{
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d %d", &n, &m);
        for(int i = 1; i <= n; i++) g[i].clear();
        memset(cnt, 0, sizeof(cnt));
        for(int i = 0; i < m; i++){
            int x,y;
            scanf("%d %d", &x, &y);
            g[y].push_back(x);
            cnt[x]++;
        }
        priority_queue<int, vector<int>, cmp> q;
        for(int i = 1; i <= n; i++) if(!cnt[i]) q.push(i);
        vector<int> res;
        while (!q.empty()) {
            int u = q.top();
            q.pop();
            res.push_back(u);
            for(int i = 0; i < g[u].size(); i++) if(--cnt[g[u][i]] == 0) q.push(g[u][i]);
        }
        if(n==1){
            printf("%d\n", 1);
        }else{
            for(int i = res.size()-1; i > 0; i--) printf("%d ", res[i]);
            printf("%d\n", res[0]);
        }
    }
    
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章