UVaOJ 10305 Ordering Tasks(拓扑排序)
来源:互联网 发布:win10对e3有优化吗 编辑:程序博客网 时间:2024/06/10 22:15
Ordering Tasks
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task isonly possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containingtwo integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is thenumber of direct precedence relations between tasks. After this, there will be m lines with two integersi and j, representing the fact that task i must be executed before task j.
An instance with n = m = 0 will finish the input.
Output
For each instance, print a line with n integers 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
题目大意:John有n个任务要做,每个任务都不是独立的,做一个任务之前必须将它的前驱任务全部做完。现在给出n个任务和m个任务关系,求出一个做任务的顺序。
解题思路:把每个任务看成点,任务之间的前后关系看成边,那么会的得到一个有向图。然后对这个图求拓扑排序即可。
代码如下:
#include <bits/stdc++.h>#define INF 1e9 + 5using namespace std;const int maxn = 10005;struct Edge{int to;int next;};Edge edge[maxn];int head[maxn],degree[maxn],topo[maxn];bool vis[maxn];int n,m,e;void init(){e = 0;memset(vis,0,sizeof(vis));memset(head,-1,sizeof(head));memset(degree,0,sizeof(degree));}void add_edge(int from,int to){degree[to]++;edge[e].to = to;edge[e].next = head[from];head[from] = e++;}void toposort(){priority_queue<int> que;for(int i = 1;i <= n;i++)if(!degree[i])que.push(i);int pos = 1;while(que.size()){int u = que.top();que.pop();topo[pos++] = u;for(int i = head[u];i != -1;i = edge[i].next){degree[edge[i].to]--;if(!degree[edge[i].to])que.push(edge[i].to);}}}int main(void){int a,b;while(scanf("%d %d",&n,&m) != EOF && n + m){init();while(m--){scanf("%d %d",&a,&b);vis[a] = vis[b] = 1;add_edge(a,b);}toposort();printf("%d",topo[1]);for(int i = 2;i <= n;i++)printf(" %d",topo[i]);printf("\n");}return 0;}
- UVaOJ 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 (拓扑排序!)
- 10305 - Ordering Tasks(拓扑排序)
- UVA - 10305 - Ordering Tasks(拓扑排序)
- UVa 10305 Ordering Tasks(拓扑排序)
- UVA 10305 Ordering Tasks(拓扑排序)
- 10305 - Ordering Tasks(****)拓扑排序
- 10305 - Ordering Tasks//拓扑排序
- Ordering Tasks(拓扑排序)
- UVaOJ 10305 - Ordering Tasks
- Ordering Tasks (拓扑排序)
- Ordering Tasks(拓扑排序)
- UVA 10305 —— Ordering Tasks(拓扑排序入门)
- 配置tomcat8
- ArrayList与Vector和HashMap与Hashtable
- 计算机网络概述
- Struts 2 拦截器应用--对运行时间较长视图界面的处理
- 【JMeter】linux下采用Jenkins、Ant实施jmeter自动化测试集成方案操作步骤(结合网上资料,纠正部分操作)
- UVaOJ 10305 Ordering Tasks(拓扑排序)
- 找到数组中只出现一次的数字
- 三范式
- ContentProvider中的ContentProviderOperation使用方法
- 【bzoj 2716】[Violet 3]天使玩偶 (cdq分治+树状数组)
- Ubuntu 常用命令
- 视图解析器的作用
- 浏览器兼容性问题
- Spark Shuffle服务和客户端