首页 > 代码库 > POJ 3687 反向建图+拓扑
POJ 3687 反向建图+拓扑
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11146 | Accepted: 3192 |
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
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
题目意思:
序列长度为n,然后m个操作 :x,y 即x在y前面, 求拓扑后的序列(使得编号小的位置数字尽可能的小)的位置。
思路:
wa了良久。。。题意没读清,说的是编号小的位置处的数字也尽可能的小,例如下面的一组数据:
1
6 4
5 6
6 1
4 3
3 2
那么拓扑后的序列为 5 6 1 4 3 2
输出位置为 3 6 5 4 1 2
看了这个样例很容易就会发现,若反向建图每次拓扑的时候从最大的开始,输出时倒着就行了。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <vector> 6 #include <queue> 7 using namespace std; 8 9 #define N 20510 11 int in[N], ans[N];12 int n, m;13 vector<int>ve[N];14 15 void init(){16 for(int i=0;i<=n;i++) ve[i].clear();17 memset(in,0,sizeof(in));18 }19 20 main()21 {22 int i, j, k, t;23 cin>>t;24 while(t--){25 scanf("%d %d",&n,&m);26 init();27 int x, y;28 while(m--){29 scanf("%d %d",&x,&y);30 ve[y].push_back(x);31 in[x]++;32 }33 int f, nn=0;34 for(i=0;i<n;i++){35 f=0;36 for(j=n;j>=1;j--){37 if(!in[j]){38 for(k=0;k<ve[j].size();k++){39 in[ve[j][k]]--;40 }41 in[j]=-1;f=1;ans[nn++]=j;42 break;43 }44 }45 if(!f) break;46 }47 if(i<n) printf("-1\n");48 else{49 int a[N];50 51 for(i=nn-1;i>=0;i--) a[ans[i]]=nn-i;52 printf("%d",a[1]);53 for(i=2;i<=nn;i++) printf(" %d",a[i]);54 55 cout<<endl;56 }57 }58 }
POJ 3687 反向建图+拓扑