Descriptioncode
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:ip
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
Inputstring
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.it
Outputio
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.class
Sample Inputtest
5map
4 0next
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
題目大意:
這道題每次輸入a,b的時候表示的是編號爲a的球比編號爲b的球輕,最後輸出的是從編號 1
到編號 n每一個小球的重量,若是存在多組解,輸出使最小重量儘可能排在前邊的那組解,亦即 全部解中 1到 n號球的重量的字典序最小。。。。
#include<stdio.h>#include<string.h>#define N 1010int map[N][N];int indegree[N];int vis[N];int a[N];int main(){ int i,j,m,n,x,y,t,p,flag; scanf("%d",&t); while(t--) { flag=0; scanf("%d%d",&n,&m); memset(map,0,sizeof(map)); memset(indegree,0,sizeof(indegree)); memset(a,0,sizeof(a)); for(i=1; i<=m; i++) { scanf("%d%d",&x,&y); if(map[x][y]==0) { map[x][y]=1; indegree[x]++;//計算出度 } } p=n; for(;;)//反向建樹 { for(i=n; i>=1; i--) if(a[i]==0&&indegree[i]==0) break; if(i==0) break; a[i]=p--; for(j=1; j<=n; j++) if(map[j][i]==1) indegree[j]--; } if(p==0) { for(i=1; i<n; i++) printf("%d ",a[i]); printf("%d\n",a[i]); } else printf("-1\n"); } return 0;}