Labeling Balls POJ3687 【拓扑排序反向建边】【邻接表】

来源:互联网 发布:广西广电网络企业邮箱 编辑:程序博客网 时间:2024/05/10 18:16

http://poj.org/problem?id=3687


Description

Windy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 to N in such a way that:

  1. No two balls share the same label.
  2. The labeling satisfies several constrains like "The ball labeled with a is lighter than the one labeled with b".

Can you help windy to find a solution?

Input

The first line of input is the number of test case. The first line of each test case contains two integers, N (1 ≤ N ≤ 200) and M (0 ≤ M ≤ 40,000). The next M line each contain two integers a and b indicating the ball labeled with a must be lighter than the one labeled with b. (1 ≤ a, b ≤ N) There is a blank line before each test case.

Output

For each test case output on a single line the balls' weights from label 1 to label N. If several solutions exist, you should output the one with the smallest weight for label 1, then with the smallest weight for label 2, then with the smallest weight for label 3 and so on... If no solution exists, output -1 instead.

Sample Input

54 04 11 14 21 22 14 12 14 13 2

Sample Output

1 2 3 4-1-12 1 3 41 3 2 4



一开始没看懂这句话,一直WA

如果存在这种拓扑排序(哪种排序呢?就是尽可能让编号小的先走,即放在前面,这种情况可以用反向建边实现,特别神奇),目前存在的一种顺序,把这个顺序重新编号,最轻的为1,然后是2,3,4,5……;就是说原来的排名顺序,开始找,找通过这次要求排序之后,输出他现在排第几了。

然而我就直接把排完序的序列输出了,最坑的是,和所给的样例是一样的。


最后排完序后,重新编号,按照原来的顺序输出,(其实可以这样理解,就是成绩表是以学号排列的,有次考试把你的班级排名写在后面,输出从头开始所有学生的排名)


#include<cstdio>#include<cstring>#include<queue>#define N 44000using namespace std;struct node {int to;int next;}arr[N];int head[N];int indegree[N];int res[N];int w[N];int n;int topo(){int i,j,k;priority_queue<int>q;//大的先出队列 for(j=1;j<=n;++j){if(indegree[j]==0){q.push(j);}}k=0;while(!q.empty()){int u=q.top();q.pop();res[k++]=u;for(j=head[u];j!=-1;j=arr[j].next){int v=arr[j].to;indegree[v]--;if(indegree[v]==0) q.push(v);}}return k;}int main(){int T,m;int i,j;int a,b;scanf("%d",&T);while(T--){scanf("%d%d",&n,&m);memset(indegree,0,sizeof(indegree));memset(head,-1,sizeof(head));for(i=1;i<=m;++i){scanf("%d%d",&a,&b);arr[i].next=head[b];//反向建 head[b]=i;arr[i].to=a;indegree[a]++;}int k=topo(); if(k<n) printf("-1\n");else {for(int i=0;i<k;i++)//从重到轻重新编号                 w[res[i]]=n-i;            printf("%d",w[1]);            for(int i=2;i<=n;i++)                printf(" %d",w[i]);            puts("");//for(i=k-1;i>0;--i)//printf("%d ",res[i]);//printf("%d\n",res[0]);}}return 0;}/*25 45 14 21 32 310 54 18 17 84 12 8ans:2 4 5 3 1        逆向建图5 1 6 2 7 8 3 4 9 10  没有判重边的话就输出 -1*/


1 0
原创粉丝点击