HDU - 1285 - 确定比赛名次(拓扑排序)

题目链接
  拓扑排序模板题。(按编号小的队伍在前输出)
1.暴力解法。首先按从小到大的顺序找到第一个入度为0的边,让它作为起点。接着让与之相连的边的入度减1。然后重复第一步,直到最后一个结点。

//https://www.cnblogs.com/shuitiangong/
#include<set>
#include<map>
#include<list>
#include<stack>
#include<queue>
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define rtl rt<<1
#define rtr rt<<1|1
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define zero(a) memset(a, 0, sizeof(a))
#define INF(a) memset(a, 0x3f, sizeof(a))
#define IOS ios::sync_with_stdio(false)
#define _test printf("==================================================\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> P2;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD =  1000000009;
const int INF = 0x3f3f3f3f;
const int maxn = 5e2+10;
int n, m, in[maxn], vis[maxn], ans[maxn], g[maxn][maxn];
void toposort() {
    for (int i = 1; i<=n; ++i) {
        for (int j = 1; j<=n; ++j)
            if (!in[j] && !vis[j]) {
                vis[j] = true;
                ans[i] = j;
                for (int k = 1; k<=n; ++k)
                    if (g[j][k]) --in[k];
                break;
            } 
    }
}
int main(void) {
    while(~scanf("%d%d", &n, &m)) {
        zero(in); zero(vis); zero(g);
        for (int i = 0, a, b; i<m; ++i) {
            scanf("%d%d", &a, &b);
            if (!g[a][b]) ++in[b]; //因为可能有重边所以这里要判断一下
            g[a][b] = 1;
        }
        toposort();
        for (int i = 1; i<=n; ++i) printf(i==n ? "%d\n" : "%d ", ans[i]);
    }
    return 0;
}

2.优先队列版本,每次取出一个入度为0且最小的结点,然后让与之相连的结点入度减1,将入度为0并且未访问过的结点加入优先队列,直到队列为空。

const int maxn = 5e2+10;
int n, m, in[maxn], vis[maxn], ans[maxn], g[maxn][maxn];
void toposort() {
    priority_queue<int, vector<int>, greater<int> > q;
    for (int i = 1; i<=n; ++i) 
        if (!in[i]) {
            q.push(i);
            vis[i] = true;
        }
    int kase = 1;
    while(!q.empty()) {
        int u = q.top(); q.pop();
        ans[kase++] = u;
        for (int i = 1; i<=n; ++i) {
            if (g[u][i]) --in[i];
            if (!in[i] && !vis[i]) {
                vis[i] = true;
                q.push(i);
            }
        }
    }
}
int main(void) {
    while(~scanf("%d%d", &n, &m)) {
        zero(in); zero(vis); zero(g);
        for (int i = 0, a, b; i<m; ++i) {
            scanf("%d%d", &a, &b);
            if (!g[a][b]) ++in[b]; //因为可能有重边所以这里要判断一下
            g[a][b] = 1;
        }
        toposort();
        for (int i = 1; i<=n; ++i) printf(i==n ? "%d\n" : "%d ", ans[i]);
    }
    return 0;
}
posted @ 2020-04-03 17:15  shuitiangong  阅读(104)  评论(0编辑  收藏  举报