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
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
题目大意 : 有N个球,标签从1到N, 每个球有各自的重量且一定互不相等,现在输入A, B表示标签为A的球比标签为B的球轻,依次输出标签从1到N的球的最小质量。
WA了将近10次才过T_T, 先说下这题有哪些坑点。 首先需要输出的不是拓扑排序后的球的标签,而是输出从1到N每个球的质量,不仔细读题的话很容易就会觉得这就是一个输出字典序的题。其次,如果正常建图的话,是没法过的,原理如下图所示:
这张图2和3都是入度为0的点,但是如果正常拓扑排序的话你怎么知道该先弹出哪个点呢?目前这张图正确的应该是弹出2,尽早的把1弹出来才对,但是不管你按照字典序大还是小排序,我都可以将2, 3互换,所以就没法得出正确答案,因为你不知道1具体在哪个位置。我们试试反向建图:
这样,我们先弹出最大的5,依次弹出4, 3, 1, 2.这时候我们按照字典序大的先弹出,就可以保证把最重的取出,剩下的一定是较轻的。
看了别人的解释发现这道题还有个坑点那就是重边的问题,如果有相同的边出现,会输出 - 1, 用链式前向星写就可以避免重边了。
AC代码 :
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1e5 + 5;
struct node
{
int v, next;
}e[maxn];
int head[maxn], dp[maxn], n, m, cnt;
int in[maxn], tot, T, X;
void init() {
memset(head, -1, sizeof(head));
memset(in, 0, sizeof(in));
memset(dp, 0, sizeof(dp));
cnt = X = 0;
tot = n;
}
void add (int from, int to) {
e[++cnt].v = to;
e[cnt].next = head[from];
head[from] = cnt;
}
void topsort() {
priority_queue <int> q;
for (int i = 1; i <= n; i++) {
if (!in[i]) q.push(i);
}
while (!q.empty()) {
int u = q.top();
q.pop();
dp[u] = tot--; // 赋予该小球目前可以赋予的最大质量
X++;
for (int i = head[u]; i != -1; i = e[i].next) {
int v = e[i].v;
in[v]--;
if (!in[v]) q.push(v);
}
}
if (X < n) cout << -1 << endl;
else {
for (int i = 1; i <= n; i++) cout << dp[i] << " ";
cout << endl;
}
}
int main()
{
cin >> T;
while (T--) {
cin >> n >> m;
init();
for (int i = 0; i < m; i++) {
int ui, vi;
cin >> ui >> vi;
add (vi, ui);
in[ui]++;
}
topsort();
}
return 0;
}