博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
poj3687——Labeling Balls(拓扑排序)
阅读量:2343 次
发布时间:2019-05-10

本文共 1875 字,大约阅读时间需要 6 分钟。

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

编号为a的球轻于b的球,求可能的重量从小到大的排序请况。越在前面的球编号尽量越小。

将轻重有关系的球建图,从编号由大到小遍历,如果有没有比它更重的球,那这个球就是最重的,并从图里去除相关的关系。

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define INF 0x3f3f3f3f#define MAXN 205#define Mod 10001using namespace std;int n,m;int mp[MAXN][MAXN],indegree[MAXN],ans[MAXN];int main(){ int t,a,b,j,i; scanf("%d",&t); while(t--) { memset(mp,0,sizeof(mp)); memset(indegree,0,sizeof(indegree)); scanf("%d%d",&n,&m); while(m--) { scanf("%d%d",&a,&b); if(!mp[b][a]) { mp[b][a]=1; indegree[a]++; } } for(i=n; i>=1; --i) { for(j=n; j>=1; --j) { if(indegree[j]==0) { indegree[j]--; ans[j]=i; for(int k=1; k<=n; ++k) if(mp[j][k]) indegree[k]--; break; } } if(j<1) break; } if(i>=1) cout<<"-1"<

转载地址:http://sxcvb.baihongyu.com/

你可能感兴趣的文章
特征向量的欧式距离与余弦距离——推荐算法
查看>>
jQuery提示和技巧
查看>>
是否可以在Python中将长行分成多行[重复]
查看>>
你什么时候使用Builder模式? [关闭]
查看>>
在jQuery中每5秒调用一次函数的最简单方法是什么? [重复]
查看>>
Angular 2+中的ngShow和ngHide等效于什么?
查看>>
如何将Java String转换为byte []?
查看>>
@Transactional注释在哪里?
查看>>
找不到Gradle DSL方法:'runProguard'
查看>>
AngularJS ngClass条件
查看>>
为什么需要在脚本文件的开头加上#!/ bin / bash?
查看>>
ReactJS-每次调用“ setState”时都会调用渲染吗?
查看>>
ng-if和ng-show / ng-hide有什么区别
查看>>
用Java复制文件的标准简洁方法?
查看>>
管理webpack中的jQuery插件依赖项
查看>>
删除可能不存在的文件的大多数pythonic方式
查看>>
如何在Eclipse中为Java文本编辑器更改字体大小?
查看>>
我们应该@Override接口的方法实现吗?
查看>>
ng-repeat定义次数而不是重复数组?
查看>>
选择语句以查找某些字段的重复项
查看>>