Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8814 | Accepted: 2387 |
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:
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
这题题意需要理解清楚,题目要求若有多种拓扑序列,则先保证第一个球最轻,其次第二个……直到最后一个。刚开始想着先根据给定的关系求一个按编号的字典序最小的序列,然后对这些球按拓扑序列依次将重量赋值为1~n。
很不幸的wa了,后来想到这样做不行,例如:对于四个球,给定4<1,则求出的字典序最小的拓扑序列为2 3 4 1,所以四个球的重量分别为4 1 2 3,显然按照题目要求四个球的重量应该分别是2 3 4 1。郁闷了一下午后,突然想通了,逆向求拓扑序列不就可以了吗?即每次都找出度为0的点,若有多个出度为0的点,找编号最大的。这样求出了一个逆向的拓扑序列后,将重量依次赋为n~1。这样这道题就圆满解决了!
#include <iostream> #include<cstdio> #include<vector> #include<queue> using namespace std; bool map[205][205]; int out[205]; void TopSort(int n) { //由于每次都要找出度为0且编号最大的球, //所以此处用优先队列维护出度为0的点 priority_queue<int>q; int weight[205],cnt=n; for(int i=1;i<=n;i++) if(out[i]==0) q.push(i); while(!q.empty()) { int elm=q.top(); q.pop(); weight[elm]=cnt--; for(int i=1;i<=n;i++) if(map[i][elm]) { out[i]--; if(out[i]==0) q.push(i); } } if(cnt>0) printf("-1\n"); else { for(int i=1;i<n;i++) printf("%d ",weight[i]); printf("%d\n",weight[n]); } } int main() { int t,n,m,i,j,a,b; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { out[i]=0; for(int j=1;j<=n;j++) map[i][j]=false; } while(m--) { scanf("%d%d",&a,&b); if(!map[a][b]) { map[a][b]=true; out[a]++; } } TopSort(n); } return 0; }