XMU 1459 排位 拓扑排序 水题

来源:互联网 发布:视频cms系统英文版 编辑:程序博客网 时间:2024/05/09 12:44
1459.排位
Time Limit: 2000 MS         Memory Limit: 65536 K
Total Submissions: 248 (75 users)         Accepted: 54 (50 users)
[ My Solution]

Description
在竞技比赛中, 为了衡量一支队伍在比赛中的能力水平, 我们常常需要使用到排位顺序的概念, 其中, 排位越靠前的队伍, 能力越强。现在, 已知n支队伍参加了某项比赛和其中一些队伍排位的先后次序关系, 你能确定出这些队伍的排名情况吗?

Input
输入的第一行有2个整数n, m (2 <= n <= 100,000, 0 <= m <= 200,000), 接下来有m行, 每行两个正整数x, y (1 <= x, y <= n, 且 x != y)代表编号为x的队伍的排位在编号为y的队伍之前。

Output
如果任何一种排位顺序都不满足要求, 则输出-1, 否则, 请按排位的先后顺序输出n支队伍的编号, 每两个数字之间保留一个空格, 若存在多种满足题意的排位顺序, 则输出任意一种都可以通过本题。

Sample Input
4 3
3 4
2 1
1 3

Sample Output
2 1 3 4

Hint
这是一道SPECIAL JUDGE的题目, C++建议使用scanf读入, printf输出

Source
doraemon @ xmu


题意:
输入 n m
n个人   m个关系  
对于每个关系a b  表示a在b的前面 
问输入这些之后  所有点的最后的前后顺序应该是什么   可以有多种答案  special judge

思路:
模板题 :拓扑排序
#include<stdio.h>#include<malloc.h>#include<queue>using namespace std;int m,n;const int mmax=100100;struct haha{int son;struct haha *nextson;}*e[mmax];int in[mmax],ans[mmax];void add_edge(int x,int y){struct haha *p;p=(struct haha *)malloc(sizeof(struct haha));p->son=y;p->nextson=e[x];e[x]=p;}int main(){int i,x,y,num,cnt;while(scanf("%d %d",&n,&m)!=EOF){num=n;cnt=0;for(i=1;i<=n;i++){e[i]=NULL;in[i]=0;}for(i=1;i<=m;i++){scanf("%d %d",&x,&y);add_edge(x,y);in[y]++;}priority_queue<int,vector<int>,greater<int> >duilie;//注意这里要把》 》 分开 写for(i=1;i<=n;i++)if(in[i]==0) duilie.push(i);while(!duilie.empty()){x=duilie.top();duilie.pop();ans[cnt++]=x;struct haha *p;p=e[x];while(p!=NULL){if(--in[p->son]==0) duilie.push(p->son);p=p->nextson;}}if(cnt!=n) {printf("-1\n");continue;} for(i=0;i<cnt-1;i++)printf("%d ",ans[i]);printf("%d\n",ans[cnt-1]);}return 0;}