HDU-1285-确定比赛名次

本文介绍了一种使用拓扑排序解决比赛排名问题的算法。通过构建比赛结果的有向图,利用优先队列实现拓扑排序,确定各比赛队的最终排名。文章提供了完整的代码示例,包括数据结构定义、拓扑排序函数实现及主函数调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://vjudge.net/problem/HDU-1285

题意:

有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。 

思路:

拓扑排序,group记录每个点赢的人,in数组记录每个点的入度。

对每个入度为0的点添加到优先队列中,同时取出来的时候把这个点赢的点的入度都减1,题目数据保证正确性。

代码:

#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>

using namespace std;

typedef long long LL;

const int MAXN = 500 + 10;

vector<int> Group[MAXN];
int in[MAXN];
int n, m;

vector<int> topo()
{
    vector<int> res;
    priority_queue<int> que;
    for (int i = 1; i <= n;i++)
        if (in[i] == 0)
            que.push(-i);

    while (!que.empty())
    {
        int now = -que.top();
        que.pop();
        res.push_back(now);
        for (auto x : Group[now])
            if (--in[x] == 0)
                que.push(-x);
    }

    return res;

}

int main()
{
    int l, r;
    while (~scanf("%d%d", &n, &m))
    {
        for (int i = 1;i <= n;i++)
            Group[i].clear();
        memset(in, 0, sizeof(in));

        for (int i = 1; i <= m; i++)
        {
            scanf("%d%d", &l, &r);
            Group[l].push_back(r);
            in[r]++;
        }

        vector<int> res = topo();
        int cnt = 0;
        for (auto x : res)
        {
            if (cnt > 0)
                cout << ' ' ;
            cout << x;
            cnt ++;
        }
        cout << endl;
    }


    return 0;
}

  

 

转载于:https://www.cnblogs.com/YDDDD/p/10486596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值