UVa 10305 Ordering Tasks 拓扑排序 解题报告
来源:互联网 发布:迅游 mac 编辑:程序博客网 时间:2024/06/05 22:39
Problem Description
John has n tasks to do. Unfortunately, thetasks are not independent and the execution of one task is
only possible if other tasks have alreadybeen executed.
Input
The input will consist of several instancesof the problem. Each instance begins with a line containing
two integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m isthe
number of direct precedence relations betweentasks. After this, there will be m lines with two integers
i and j, representing the fact that task imust be executed before task j.
An instance with n = m = 0 will finish theinput.
Output
For each instance, print a line with nintegers representing the tasks in a possible order of execution.
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3
分析:
题意:假设有n个变量,还有m个二元组(u,v),分别表示变量u小于v。那么,所有变量从小到大排列起来应该是什么样子的呢?
把每个变量看成一个点,“小于”关系看成有向边,则得到了一个有向图。这样,我们的任务实际上是把一个图的所有结点排序,使得每一条有向边(u,v)对应的u都排在v的前面。
用dfs完成拓扑排序,在访问完一个结点之后吧它加到当前拓扑序的首部。
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define max 100+5 int c[max],topo[max],t,n,G[max][max]; int dfs(int u) { int v; c[u] = -1; //访问标志,-1为正在访问,0是未访问,1是已经访问 for(v = 1; v <= n; v++) if(G[u][v]) { if(c[v] < 0) return 0; else if(!c[v] && !dfs(v)) return 0; } c[u] = 1; topo[--t] = u; return 1; } int toposort() { int i; t = n; memset(c,0,sizeof(c)); for(i = 1; i <= n; i++) if(!c[i] && !dfs(i)) return 0; return 1; } int main() { int m,i; while(scanf("%d%d",&n,&m),n || m) { int u,v; memset(G,0,sizeof(G)); for(i = 0 ; i < m ; i++) { scanf("%d%d",&u,&v); G[u][v] = 1; } if(toposort()) { for(i = 0; i < n-1; i++) printf("%d ",topo[i]); printf("%d\n",topo[i]); } } return 0; }
- UVa 10305 Ordering Tasks 拓扑排序 解题报告
- uva 10305 Ordering Tasks(拓扑排序)
- uva 10305 Ordering Tasks (拓扑排序)
- UVa 10305 Ordering Tasks (拓扑排序模板)
- [UVA 10305] Ordering Tasks (拓扑排序)
- UVa 10305 - Ordering Tasks 拓扑排序
- UVa 10305 Ordering Tasks(拓扑排序)
- UVa 10305 - Ordering Tasks 拓扑排序题解
- UVA - 10305 Ordering Tasks (拓扑排序)
- Ordering Tasks - UVa 10305 拓扑排序
- Uva 10305 Ordering Tasks(拓扑排序)
- Ordering Tasks From:UVA, 10305(拓扑排序)
- UVa 10305 - Ordering Tasks(拓扑排序)
- UVA - 10305 - Ordering Tasks (拓扑排序!)
- UVA - 10305 (Ordering Tasks) 拓扑排序
- UVa 10305 Ordering Tasks(拓扑排序)
- UVA 10305- Ordering Tasks(经典拓扑排序)
- uva 10305 Ordering Tasks 【拓扑排序】
- 在win2012r2上安装KMS模拟器和IDEA激活模拟器并设置开机自启
- 2014年山东省第五届ACM--Weighted Median
- QT5 for android 实现横屏锁定
- 面试时如何自我介绍【面试核心问题1】
- 关于php执行shell脚本
- UVa 10305 Ordering Tasks 拓扑排序 解题报告
- 蓝桥杯—— 算法训练 图形显示
- 利用kettle对postgresql进行批量加载
- union是什么【编写一个判断大端小段c程序】
- Android将图片打成圆形
- poj 3624(01背包)
- 自定义弹窗
- Jquery第二步
- 使用SWIG自动生成JNI代码