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?
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.
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.
5 4 0 4 1 1 1 4 2 1 2 2 1 4 1 2 1 4 1 3 2Sample Output
1 2 3 4 -1 -1 2 1 3 4 1 3 2 4
题意:刚看这个题觉得和 HDU - 4857 逃生 https://blog.youkuaiyun.com/dsaghjkye/article/details/80000776 一模一样,就多了
个如果有冲突输出-1,后来错了两次,重读题意发现他要输出的是每个球的质量而不是排序是怎么样,这两道题意思还是一样的,输入 u v 按 v到 u 建边 a[u]++ (代表u的出度++), 把所有出度为0的放入优先队列(大的先输出) ,显然先输出的排序应该在最后面,即越重
#include<stdio.h>
#include<string>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
int t,n,m,tot,cnt;
struct node
{
int en,next;
}e[44000];
int a[4000];
int p[4000];
int ans[4000];
void init()
{
memset(p,-1,sizeof(p));
memset(a,0,sizeof(a));
tot=0;
cnt=0;
}
void add(int u,int v)
{
e[tot].en=v;
e[tot].next=p[u];
p[u]=tot++;
}
int main()
{
int u,v;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(v,u);
a[u]++;
}
priority_queue<int,vector<int>,less<int> >q;//大的优先
for(int i=1;i<=n;i++)
{
if(!a[i]) q.push(i);
}
while(!q.empty())
{
u=q.top();
q.pop();
cnt++;
ans[u]=n-cnt+1;//显然最先输出质量最重
for(int i=p[u];i+1;i=e[i].next)
{
v=e[i].en;
a[v]--;
if(!a[v])
q.push(v);
}
}
if(cnt!=n)//说明有环
printf("-1\n");
else
{
for(int i=1;i<=n;i++)
{
if(i!=1) printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
}
}
本文介绍了一个球排序问题的算法解决方案,通过构建图模型并利用优先队列实现最优排序,最终输出每个球的质量。该问题涉及图论、优先队列及拓扑排序等计算机科学概念。
469

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



