码迷,mamicode.com
首页 > 编程语言 > 详细

Labeling Balls(拓扑排序wa)

时间:2015-09-19 22:29:38      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:

Labeling Balls
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12466   Accepted: 3576

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
题解:反向建图,却是wa。。。先放着吧
wa代码:
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<queue>
 4 #define mem(x,y) memset(x,y,sizeof(x)) 
 5 using namespace std;
 6 const int MAXN=210;
 7 const int MAXM=40010<<1;
 8 int head[MAXM];
 9 int que[MAXN],ans[MAXN];
10 struct Edge{
11     int from,to,next;
12 }; 
13 Edge edg[MAXM];
14 int edgnum;
15 int N;
16 void add(int u,int v){
17     Edge E={u,v,head[u]};
18     edg[edgnum]=E;
19     head[u]=edgnum++;
20 } 
21 void topu(){
22     priority_queue<int>dl;
23     int top=1;
24     for(int i=1;i<=N;i++)
25         if(!que[i])dl.push(i);
26     while(!dl.empty()){
27         int k=dl.top();
28         dl.pop();
29         ans[top++]=k;
30         que[k]=-1;
31         for(int i=head[k];i!=-1;i=edg[i].next){
32             int v=edg[i].to;
33             que[v]--;
34             if(!que[v])dl.push(v);
35         }
36     }
37     if(top!=N+1)puts("-1");
38     else{
39     for(int i=N;i>=1;i--){
40         if(i!=N)printf(" ");
41         printf("%d",ans[i]);
42     }
43     puts("");
44     }
45 }
46 int main(){
47     int T,M,a,b;
48     scanf("%d",&T);
49     while(T--){
50         scanf("%d%d",&N,&M);
51         for(int i=1;i<=N;i++)ans[i]=i;
52         mem(que,0);
53         mem(head,-1);
54         edgnum=0;
55         while(M--){
56             scanf("%d%d",&a,&b);
57             add(b,a);//
58             que[a]++;//反向建图 
59         }
60         topu();
61     }
62     return 0;
63 }

 

Labeling Balls(拓扑排序wa)

标签:

原文地址:http://www.cnblogs.com/handsomecui/p/4822313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!