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
题意是输入的球的关系为前一个比后一个轻,而题目要求把重的球放到后面,轻的球在前面且序号小的在前面,所以需要反向的拓扑排序。最后输出每个球所在的位置。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INF 0x3f3f3f3f
using namespace std;
int du[255];
int map[255][255];
int vis[255];
int ans[255];
int main()
{
int n,m,x,y;
int t,i,j,k;
scanf("%d",&t);
while (t--)
{
memset(map,0,sizeof(map));
memset(du,0,sizeof(du));
scanf("%d%d",&n,&m);
for (i=0; i<m; i++)
{
scanf("%d%d",&x,&y);
if(!map[y][x])
{
map[y][x]=1;
du[x]++;
}
}
int flag;
for (i=n; i>=1; i--)
{
flag=1;
for (j=n; j>=1; j--)
{
if(du[j]==0)
{
flag=0;
ans[j]=i;
du[j]=-1;
for (k=1; k<=n; k++)
{
if(map[j][k])
du[k]--;
}
break;
}
}
if (flag) break;
}
if(flag)
{
printf("-1\n");
}
else
{
for (i=1; i<=n; i++)
{
printf("%d%c",ans[i],i==n?'\n':' ');
}
}
}
return 0;
}
球排序算法实现

本文介绍了一种基于球的重量进行排序的算法实现,通过输入球之间的重量关系,采用反向拓扑排序的方法来确定每颗球正确的标签位置,确保了重的球被标记在后面,轻的球被标记在前面,并提供了具体的C++代码实现。
764

被折叠的 条评论
为什么被折叠?



