HDU 1285 确定比赛名次 拓扑排序模板题

http://acm.hdu.edu.cn/showproblem.php?pid=1285

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <assert.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;


#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
int n, m;
const int maxn = 500 + 20;
struct node {
    int u, v;
    int tonext;
}e[maxn * 2];
int first[maxn];
int num;
int in[maxn];
void add(int u, int v) {
    ++num;
    e[num].u = u;
    e[num].v = v;
    e[num].tonext = first[u];
    first[u] = num;
}
struct DAG {
    int cur;
    bool operator < (const struct DAG & rhs) const {
        return cur > rhs.cur;
    }
    DAG(int ccur) : cur(ccur) {};
};
vector<int>ans;
priority_queue<struct DAG> que;
bool DAG_sort() {
    for (int i = 1; i <= n; ++i) { //节点号小的在前
        if (in[i] == 0) que.push(DAG(i));
    }
    while (!que.empty()) {
        int cur = que.top().cur;
        que.pop();
        ans.push_back(cur);
        for (int i = first[cur]; i; i = e[i].tonext) {
            int v = e[i].v;
            in[v]--;
            if (in[v] == 0) que.push(DAG(v));
        }
    }
    if (ans.size() < n) return false; //有环
    return true;
}
void init() {
    num = 0;
    memset(first, 0, sizeof first);
    ans.clear();
    memset(in, 0, sizeof in);
}
void work() {
    init();
    for (int i = 1; i <= m; ++i) {
        int u, v;
        scanf("%d%d", &u, &v);
        add(u, v);
        in[v]++;
    }
    DAG_sort();
    for (int i = 0; i < ans.size() - 1; ++i) {
        printf("%d ", ans[i]);
    }
    printf("%d
", ans.back());
}

int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    while (scanf("%d%d", &n, &m) != EOF) work();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/liuweimingcprogram/p/6257792.html