Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15151 | Accepted: 4420 |
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
解题思路:拓扑排序模板题,用于保存模板!……拓扑排序很简单,具体思想就是,不断地找入度为0的点,然后删除该点,和该点的出边,直到找不到入度为0的点为止。如果做到最后,发现还有点没有被访问过,那么证明有环。
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <memory.h>
#include <bitset>
#include <map>
#include <deque>
#include <math.h>
#include <stdio.h>
#include <stack>
using namespace std;
using namespace std;
typedef long long int ll;
const int MAXN = 300005;
int N, M;
int indegree[205];
int G[205][205];
int ans[205];
bool flag;
void topologysort()
{
int i, k = N;
while (k >= 1)
{
for (i = N; i >= 1; i--)
{
if (indegree[i] == 0)
{
for (int j = 1; j <= N; j++)
if (G[i][j] == 1)
indegree[j]--;
indegree[i]=-1;
ans[i] = k--;
break;
}
}
if (i == 0)//有环
{
flag = 0;
break;
}
}
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
flag = 1;
memset(G, 0, sizeof(G));
memset(indegree, 0, sizeof(indegree));
scanf("%d%d", &N, &M);
int a, b;
for (int i = 0; i < M; i++)
{
scanf("%d%d", &a, &b);
if (G[b][a] == 0)
{
G[b][a] = 1;
indegree[a]++;
}
}
topologysort();
if (flag)
{
for (int i = 1; i < N; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[N]);
}
else
{
printf("-1\n");
}
}
return 0;
}
//更快的优先队列实现
bool isLoop(int N) //G是邻接表
{
stack<int> s;
int i,k;
for(i=1;i<=N;i++)
{
if(!indegree[i])
s.push(i); //入度为零的节点入栈
}
int count=0;
while(!s.empty())
{
i = s.top();
s.pop();
count++; //统计遍历过的节点个数
for(int p=head[i];~p;p=e[p].next)
{
indegree[e[p].v2]--;
if(!indegree[e[p].v2])
s.push(e[p].v2);
}
}
if(count==N)
return false;
return true;
}