Labeling Balls
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 11256 |
|
Accepted: 3230 |
Description
Windy have n balls of distinct weights from 1 unit to N units. Now the he tries to the label them with 1 to N in such a by that:
- No. Balls share the same label.
- The labeling satisfies several constrains like "the ball labeled with a are lighter than the one labeled with b ".
Can windy to find a solution?
Input
The first line of input was the number of the test case. The first line of all test case contains-integers, n (1≤ n ≤200) and m (0≤ m ≤ 40,000). The next M line each contain, integers a and B indicating the ball labeled with a must is lighter than the one labeled with b. (1≤ A, b ≤ N) There is a blank line before each test case.
Output
For each test, the output on a, 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
Test instructions: There is a T group test data, the first row of each group of test data has two number n,m. The Representative has n Ball, next m line, each row has two number A, a, represents a ball lighter than B ball, let you from small to large output ball weight, if the same weight, according to the dictionary order output.
Idea: This is slightly different from the previous topological order, not considering the 0-degree situation. Since n is assumed to be 4,4<1. The output column is 2,3,4,1, not the 4,1,2,3 as previously mentioned. So the first thing to consider is to put the heaviest in the back, light in front of the dictionary sequence output can be.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include < algorithm> #include <queue> #include <set>using namespace Std;int map[210][210];int out[210];void topo ( int n) {int i; int cnt=n; int weight[210]; Priority_queue<int >q;//Priority queue, in order from large to small. for (i=1;i<=n;i++) {if (out[i]==0) Q.push (i); } while (!q.empty ()) {int k=q.top (); Q.pop (); weight[k]=cnt--; for (i=1;i<=n;i++) {if (Map[i][k]) {out[i]--; if (out[i]==0) Q.push (i); }}} if (cnt>0) printf (" -1\n"); else{for (i=1;i<n;i++) printf ("%d", weight[i]); printf ("%d\n", Weight[i]); }}int Main () {int t,n,m,i,j; int A, B; scanf ("%d", &t); while (t--) {scanf ("%d%d", &n,&m); Memset (out,0,sizeof (out)); memset (map,0,sizeof (map)); while (M--) {scanf ("%d%d", &a,&b); if (map[a][b]==0) {map[a][b]=1; out[a]++; }} topo (n); } return 0;}
POJ 3687-labeling Balls (reverse order topology)