HDUOJ 1285-- 确定比赛名次

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1285
确定比赛名次
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36816 Accepted Submission(s): 14389

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

Input
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。

Output
给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。

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

Sample Input
4 3
1 2
2 3
4 3

Sample Output
1 2 4 3
题解:
这道题是对拓扑排序的一个应用,但是需要注意的是要求输出编号小的队伍在前。含义就是在不影响前后顺序的情况下小编号在前,也就是把最后多可能的答案缩小到了只有一种情况。这时候就在原先的方法上用set来保存入度为0的顶点就可以了,因为set容器的一个作用就是自动排序,并且默认是按升序的方式排序。

另外还要注意的是虽然题目中没有说明要输出换行符,但是最后也要输出。
代码如下:

#include <bits/stdc++.h>
using namespace std;
int n,m;
const int maxn=1000;
const int maxm=1000;
struct edges
{
    int to;
    edges(int _to):to(_to){}
};
vector<edges>E[maxn];
set <int>que;
queue <int>e;   //最终存入e队列
int indegree[maxn];

void solve()
{
    for(int i=0;i<n;i++) if(indegree[i]==0) que.insert(i);
    while(!que.empty())
    {
        int a=*que.begin();e.push(a);que.erase(a);
        for(int j=0;j<(int)E[a].size();j++)
        {
            indegree[E[a][j].to]--;
            if(indegree[E[a][j].to]==0) que.insert(E[a][j].to);
        }
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        memset(indegree,0,sizeof indegree);
        for(int i=0;i<1000;i++) E[i].clear();
        while(!que.empty())que.clear();
        while(!e.empty())e.pop();
        for(int i=0;i<m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            E[a-1].push_back(edges(b-1));
            indegree[b-1]++;
        }
        solve();
        cout<<(e.front()+1);
        e.pop();
        while(!e.empty()){
            cout<<' '<<(e.front()+1);
            e.pop();
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35937273/article/details/81870803