首页 > 编程语言 > 详细

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

时间:2020-04-03 17:22:19      阅读:58      评论:0      收藏:0      [点我收藏+]

题目链接
??拓扑排序模板题。(按编号小的队伍在前输出)
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;
}

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

原文:https://www.cnblogs.com/shuitiangong/p/12627631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!