POJ3687 Labeling Balls

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13645   Accepted: 3955

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

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

Source

输出满足所给限制条件的小球编号,要求靠前的球编号尽可能小。

转换思路,将靠后的球标记得尽可能大。根据题目关系反向建边,做类似拓扑排序的操作即可。(不能像一般的拓扑排序一样,将入度为0的点压进栈挨个处理,而应每次找入度为0的最靠后的点来处理,因为每个点处理完,都可能解锁新的较靠后的点)。

 1 /*by SilverN*/
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 using namespace std;
 8 const int mxn=50000;
 9 struct edge{
10     int v,next;
11 }e[mxn];
12 int hd[mxn],cnt;
13 int in[mxn];
14 int ans[mxn];
15 int n,m;
16 void add_edge(int u,int v){
17     e[++cnt].v=v;e[cnt].next=hd[u];hd[u]=cnt;
18 }
19 int st[mxn],top;
20 int vis[mxn];
21 void tp(){
22     top=0;
23     int tot=0;
24     int i,j;
25     while(1){
26         if(tot>=n)break;
27         for(i=n;i>=1;i--){//每次找最靠后的可行点 
28             if(!in[i] && !vis[i]){st[++top]=i,vis[i]=1;break;}
29         }
30         if(!top){
31             printf("-1
");
32             return;
33         }
34         while(top){
35             int u=st[top--];
36             for(i=hd[u];i;i=e[i].next){
37                 in[e[i].v]--;
38             }
39             ans[u]=++tot;
40         }
41     }
42     for(i=1;i<=n;i++){
43         printf("%d ",n+1-ans[i]);
44     }
45     printf("
");
46     return;
47 }
48 int main(){
49     int T;
50     scanf("%d",&T);
51     while(T--){
52         memset(e,0,sizeof e);
53         memset(hd,0,sizeof hd);
54         memset(in,0,sizeof in);
55         memset(vis,0,sizeof vis);
56         cnt=0;
57         scanf("%d%d",&n,&m);
58         int i,j;int a,b;
59         for(i=1;i<=m;i++){
60             scanf("%d%d",&a,&b);
61             add_edge(b,a);
62             in[a]++;
63         }
64         tp();
65     }
66     return 0;
67 }
原文地址:https://www.cnblogs.com/SilverNebula/p/5774705.html