HDU-1285-确定比赛名次(拓扑排序+优先队列)

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


思路:很显然的拓扑排序,因为“排名一样时要求输出时编号小的队伍在前”,所以用优先队列就OK。

优先队列请看:https://blog.csdn.net/c20182030/article/details/70757660

坑点:1.容器每次样例要清空  2.每组样例输出一行...


 1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 #include<vector>
 5 #define N 505
 6 using namespace std;
 7 int d[N];
 8 vector<int>G[N]; 
 9 int n,m;
10 
11 void TPsort(){
12     priority_queue<int,vector<int>,greater<int> > q;//从小到大 
13     for(int i=1;i<=n;i++)
14         if(!d[i]) q.push(i);
15     int cnt=0;    
16     while(!q.empty()){
17         int u=q.top();
18         q.pop();
19         if(!cnt) printf("%d",u);
20         else printf(" %d",u);
21         cnt++;
22         for(int i=0;i<G[u].size();i++){
23             int v=G[u][i];
24             d[v]--;
25             if(d[v]==0) q.push(v);            
26         }               
27     }    
28 }
29 
30 int main(){
31     while(~scanf("%d%d",&n,&m)){        
32            memset(d,0,sizeof(d));
33            for(int i=1;i<=n;i++)//要清理容器 
34             G[i].clear();
35         
36         for(int i=0;i<m;i++){
37         int u,v;
38         scanf("%d%d",&u,&v);
39         G[u].push_back(v);
40         d[v]++;                
41         }
42         TPsort();
43         printf("
");//注意 
44     }
45     return 0;
46 } 
原文地址:https://www.cnblogs.com/yzhhh/p/9985511.html