Time Limit: 1000MS | Memory Limit: 65536K |
Description
Windy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 toN 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 withb".
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 nextM line each contain two integers a and b indicating the ball labeled witha 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 labelN. 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
————————————————————集训8.1的分割线————————————————————
题意:仔细看题,输出的是编号1~N的球的重量。也就是说按约束关系求出球的编号的拓扑序之后,输出1~N号球在拓扑序当中的位置。其中1号球尽量轻、2号球尽量轻……依次类推。
思路:如果按照正向建图的话,无论如何都无法保证1号球尽量轻,因为我先取出了字典序最小的入度为0的点,确保它在入度1的点前面,那么假如与它相连的点编号比1大,又比1的前趋小的点就会提前于1号被取出。也就是说纯粹考虑拓扑序(拓扑序不能保证字典序小的最轻,只能保证轻的在重的前面)。但是如果反过来,我将字典序最大的出度为0的点先选出来,那么我就可以保证编号小的排在最前面。我优先保证了字典序大的放在后面。
换句话说,我就是把所有编号比1大的可以比1号重的球都放在后面了。
代码如下:
/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
/****************************************/
const int N = 205;
int n, m, indeg[N], path[N];
bool G[N][N];
bool All_topsort(int cnt)
{
if(cnt == n+1) {
for(int i = 1; i < n; i++)
printf("%d ", path[i]);
printf("%d\n", path[n]);
return true;
}
for(int i = n; i > 0; i--) if(!indeg[i]) {
path[i] = n - cnt + 1;//技巧:保存的是重量(拓扑序的位置)而不是编号
indeg[i] = -1;
for(int j = 1; j <= n; j++) if(G[j][i]) {
indeg[j]--;
}
if(All_topsort(cnt+1)) return true;
else return false;
indeg[i] = 0;
for(int j = 1; j <= n; j++) if(G[j][i]) {
indeg[j]--;
}
}
return false;
}
int main()
{
#ifdef J_Sure
freopen("3687.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
int T;
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &m);
memset(G, 0, sizeof(G));
memset(indeg, 0, sizeof(indeg));
int a, b;
for(int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
if(!G[a][b]) {
indeg[a]++;
//printf("Create %d->%d\n", a, b);
G[a][b] = true;
}
}
if(!All_topsort(1))
puts("-1");
}
return 0;
}