#逆拓扑排序# POJ 3687 Labeling Balls

题目链接

                                                                                         Labeling Balls

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 15755   Accepted: 4617

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 bindicating 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
   
     

题目描述:

有T组测试数据,每组测试数据第一行有两个数n,m。代表有n个球,接下来m行,每行有两个数x、y,代表x球比y球轻。输出n个球的重量,若有相同重量则按照球编号的字典序输出

 

Solution:

n个球的重量为1-n,首先考虑的把最重的放在后面,轻的在前面按照编号的字典序输出,也就是逆拓扑排序。

 

代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define mst(a, b) memset(a, b, sizeof(a))
#define rush() int T; scanf("%d", &T); while(T--)
using namespace std;
typedef pair PII;
const int MaxN = 205;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;

//priority_queue, greater > que;
vector res;
vector G[205];
int ans[MaxN];
int n, m, cnt;
int ind[205];

void topo() {
	priority_queue que; //从大到小排序
	cnt = n;
	for(int i = 1; i <= n; i++) 
		if(ind[i] == 0) que.push(i);
	while(!que.empty()) {
		int u = que.top(); que.pop();
		ans[u] = cnt--;
		for(int i = 0; i < G[u].size(); i++) {
			int v = G[u][i];
			if(--ind[v] == 0) que.push(v);
		}
	}
}
int main()
{
	rush() {
		mst(G, 0);
		mst(ind, 0);
		scanf("%d %d", &n, &m);
		while(m--) {
			int x, y; scanf("%d %d", &x, &y);
			G[y].push_back(x);
			ind[x]++; //需要将轻的放在前面, 重的后放
		}
		topo();
		if(cnt > 0) printf("-1\n");
		else {
			for(int i = 1; i <= n; i++) {
				printf("%d", ans[i]);
				i == n ? printf("\n") : printf(" ");
			}
		}
	}
	return 0;
}

 

 

 

 

 

 

 

你可能感兴趣的:(数据结构)