UVa 10305 Ordering Tasks

来源:互联网 发布:菲凡软件 编辑:程序博客网 时间:2024/06/11 16:57
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is
only 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 containing
two integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is the
number of direct precedence relations between tasks. After this, there will be m lines with two integers
i 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
1
2
1
1
0
4
2
3
3
5
0
Sample Output

1 4 2 5 3


#include <cstdio>#include <cstring>#include <cstdlib>#include <stack>using namespace std;// 建立任务节点结构体typedef struct v_node{int num;// 代表自身任务号int enter_num;// 指向该节点的任务数bool visit;// 遍历时是否被访问过struct v_node* child[120];// 该节点指向的任务指针int child_num;// 指向的任务数目}v_node;v_node* node_array[120];void dfs_search(v_node* p);stack<int> my_stack;int main(){int n, m;while(scanf("%d%d", &n, &m) == 2 && !(n == 0 && m == 0)){memset(node_array, 0, sizeof(node_array));my_stack = stack<int>();if(n == 0)continue;// 建立对应任务节点for(int i = 1; i <= n; i++){v_node* p = (v_node*)malloc(sizeof(v_node));memset(p, 0, sizeof(p));p->num = i;p->enter_num = 0;p->child_num = 0;p->visit = false;node_array[i] = p;}// 读入对应任务依赖关系for(int i = 1; i <= m; i++){int x1, x2;scanf("%d %d", &x1, &x2);// 被依赖任务指向依赖任务node_array[x1]->child[node_array[x1]->child_num] = node_array[x2];node_array[x1]->child_num++;node_array[x2]->enter_num++;}// 对于没有入边的那些点进行深度优先搜索,确定任务执行顺序//int first_time = 1;for(int i = 1; i <= n; i++){if(node_array[i]->visit == false && node_array[i]->enter_num == 0){/*{if(first_time){printf("%d", i);first_time = 0;}elseprintf(" %d", i);*/node_array[i]->visit = true;dfs_search(node_array[i]);}}int first_time = 1;while(my_stack.size() > 0){if(first_time){printf("%d", my_stack.top());first_time = 0;}elseprintf(" %d", my_stack.top());my_stack.pop();}printf("\n");}return 0;}// 对于没有入边的那些点进行深度优先搜索,确定任务执行顺序void dfs_search(v_node* p){// 遍历自己指向的节点for(int i = 0; i < p->child_num; i++){// 如果该点的入边遍历完了,就遍历该点//p->child[i]->enter_num--;/*if(p->child[i]->enter_num == 0)*/if(p->child[i]->visit == false){//printf(" %d", p->child[i]->num);p->child[i]->visit = true;dfs_search(p->child[i]);}}my_stack.push(p->num);}



题目很简单,拓扑排序。用DFS做。

自己想的方法是维护每个点的入度,然后遍历的时候每碰到一个点,就将其入度减一,减为0时再遍历该点。


另外一种方法是直接遍历,然后在遍历完自己的周围节点以后,将自己放入队列末尾或者栈顶。感觉很巧妙。

0 0
原创粉丝点击