【杭电】[1285]确定比赛名次

来源:互联网 发布:到印度做软件 编辑:程序博客网 时间:2024/05/19 02:28

确定比赛名次

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 31 22 34 3
 
Sample Output
1 2 4 3


拓扑排序模板题

寻找入度为0的点,存入topo数组,删除它与它相连的边,然后把与它相连的点入度减少1

最终topo即为所求排序后的数组

运用邻接表优化存储


#include<cstdio>#include<cstdlib>#include<cstring>using namespace std;int n;int cnt[520];int topo[520];struct node {int next;int to;} a[520];int head[520];void toposort() {int top,t=0;for(int i=0; i<n; i++) {for(int j=1; j<=n; j++) {if(cnt[j]==0) {top=j;break;}}topo[t++]=top;cnt[top]=-1;for(int j=head[top]; j!=-1; j=a[j].next) {cnt[a[j].to]--;}}}int main() {int m;while(scanf("%d %d",&n,&m)!=EOF) {memset(cnt,0,sizeof(cnt));memset(head,-1,sizeof(head));for(int i=0; i<m; i++) {int u,v;scanf("%d %d",&u,&v);a[i].to=v;a[i].next=head[u];head[u]=i;cnt[v]++;}toposort();for(int i=0; i<n; i++)printf("%d%c",topo[i],i==n-1?'\n':' ');}return 0;}

题目地址:【杭电】[1285]确定比赛名次

0 0
原创粉丝点击