poj 3687--Labeling Balls

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 Mline 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

只能说这题的样例数据太强了- -就算你用正向拓扑答案也和样例一样。。就这么被光荣的误导了。。这题还有一个很大的bug就是
最后输出的是每个编号球的重量而不是编号的序号- -。。。虽然我没犯这个错误。。但我也没想到要用逆向拓扑、还是看了别人的
blog才知道的。唉。长见识了。。
View Code
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <queue>
 5 using namespace std;
 6 struct edge
 7 {
 8     int v;
 9     int next;
10 }e[210*210];
11 int cnt;
12 int map[210][210],first[210];
13 int in[210],n,m,rank[210];
14 void add(int u,int v)
15 {
16     e[cnt].v=v;
17     e[cnt].next=first[u];
18     first[u]=cnt++;
19 }
20 int Topo()
21 {
22         int i,j;
23     for(i=n;i>=1;i--)
24     {
25         for(j=n;j>=1;j--)
26         {
27             if(in[j]==0)
28             {
29                 in[j]=-1;
30                 rank[j]=i;
31                 break;
32             }
33         }
34         if(j==0)
35             return 0;
36         for(j=first[j];j!=-1;j=e[j].next)
37             in[e[j].v]--;
38     }
39     return 1;
40 }
41 int main()
42 {
43     int i,j,t,u,v;
44     scanf("%d",&t);
45     while(t--)
46     {
47         cnt=1;
48         scanf("%d%d",&n,&m);
49         memset(in,0,sizeof(in));
50         memset(map,0,sizeof(map));
51     memset(first,-1,sizeof(first));
52         while(m--)
53         {
54             scanf("%d%d",&u,&v);
55             if(!map[v][u])
56             {
57                 add(v,u);
58         map[v][u]=1;
59                 in[u]++;
60             }
61         }
62         if(Topo())
63         {
64             printf("%d",rank[1]);
65             for(i=2;i<=n;i++)
66                 printf(" %d",rank[i]);
67             printf("\n");
68         }
69         else
70             printf("-1\n");
71     }
72     return 0;
73 }

 

posted @ 2013-04-03 12:45  Tamara.c  阅读(170)  评论(0编辑  收藏  举报