2117 Problem B 确定比赛名次

本文介绍了一种通过比赛胜负记录来确定多个队伍排名的方法。利用图论中的拓扑排序算法,实现了对N个队伍(N≤500)比赛结果的数据处理,确保每个胜利者在被击败者之前排名。代码采用C++实现,并通过了性能测试。

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

问题 B: 确定比赛名次
时间限制: 1 Sec 内存限制: 32 MB
献花: 56 解决: 38
[献花][花圈][TK题库]
题目描述
有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
输入
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。
输出

给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。

样例输入
3 2
3 1
3 2
17 16
16 1
13 2
7 3
12 4
12 5
17 6
10 7
11 8
11 9
16 10
13 11
15 12
15 13
17 14
17 15
17 16
0 0
样例输出
3 1 2
17 6 14 15 12 4 5 13 2 11 8 9 16 1 10 7 3

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cfloat>
#include <iomanip>
#include <map>
#include <functional>

#define INF INT32_MAX
using namespace std;


const int MaxN = 510;
int G[MaxN][MaxN];
int InDegree[MaxN] = { 0 };
queue<int>res;
int N;

bool TopSort()
{
    for (int i = 1; i <= N; ++i)
    {
        for (int k = 1; k <= N; ++k)
        {
            if (G[i][k])
                ++InDegree[k];
        }
    }

    priority_queue<int,vector<int>,greater<int>> que;
    for (int i = 1; i <= N; ++i)
    {
        if (!InDegree[i])
            que.push(i);
    }

    int count = 0;

    while (que.size())
    {
        while (que.size())
        {
            int u = que.top(); que.pop();
            res.push(u); ++count;
            for (int k = 0; k < N; ++k)
            {
                if (G[u][k])
                {
                    --InDegree[k];
                    if (!InDegree[k])
                        que.push(k);
                }
            }
        }
    }

    if (count < N)return false;
    return true;
}


void QueClear(queue<int> que)
{
    while (que.size())que.pop();
}


int main()
{
#ifdef _DEBUG
    freopen("data.txt", "r+", stdin);
#endif // _DEBUG

    std::ios::sync_with_stdio(false);

    int M;
    while (cin >> N >> M)
    {
        QueClear(res);
        fill(G[0], G[0] + (N + 2) * MaxN, 0);
        for (int i = 0; i < M; ++i)
        {
            int u, v;
            cin >> u >> v;
            G[u][v] = 1;
        }

        TopSort();
        while (res.size())
        {
            cout << res.front() << " "; res.pop();
        }
        cout << endl;
    }


    return 0;
}
/**************************************************************
    Problem: 2117
    User: Sharwen
    Language: C++
    Result: 升仙
    Time:51 ms
    Memory:2736 kb
****************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值