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:
- No two balls share the same label.
- 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
5 4 0 4 1 1 1 4 2 1 2 2 1 4 1 2 1 4 1 3 2
Sample Output
1 2 3 4 -1 -1 2 1 3 4 1 3 2 4
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
一开始没看懂这句话,一直WA,
如果存在这种拓扑排序,目前存在的这种序列重新编号,最轻的为1,然后是2,3,4,5……;就是说原来的排名顺序,通过这次要求排序之后时,输出他现在排第几了。然而我就直接把排完序的序列输出了,最坑的是,和所给的样例是一样的。
#include<cstdio> #include<cstring> #include<queue> #define N 44000 using 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; } /* 2 5 4 5 1 4 2 1 3 2 3 10 5 4 1 8 1 7 8 4 1 2 8 ans: 2 4 5 3 1 逆向建图 5 1 6 2 7 8 3 4 9 10 没有判重边的话就输出 -1 */
版权声明:本文为博主原创文章,未经博主允许不得转载。