uva 10305 Ordering Tasks 【拓扑排序】

来源:互联网 发布:淘宝 零食 知乎 编辑:程序博客网 时间:2024/05/22 16:38

10305 Ordering Tasks
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 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3

#include<stdio.h>  #include<iostream>  #include<string.h>  #include<math.h>  #include<stdlib.h>  #include<ctype.h>  #include<algorithm>  #include<vector>  #include<string>  #include<queue>  #include<stack>  #include<set>using namespace std;int n, m, r[600], a[600][600], ans[600];void toposort(){    for (int i = 1; i <= n; i++)    {        int k = 1;        while (r[k] != 0)            k++;        ans[i] = k;        r[k] = -1;        for (int j = 1; j <= n; j++)        {            if (a[k][j])                r[j]--;        }    }}int main(){    int x, y;    while (scanf("%d%d", &n, &m) != EOF)    {        if (n == 0 && m == 0)            return 0;        memset(a, 0, sizeof(a));        memset(r, 0, sizeof(r));        for (int i = 1; i <= m; i++)        {            scanf("%d %d", &x, &y);            if (a[x][y] == 0)            {                a[x][y] = 1;            }        }        for (int i = 1; i <= n; i++)            for (int j = 1; j <= n; j++)            {                if (a[i][j] != 0)                    r[j]++;            }        toposort();        for (int i = 1; i <= n; i++)        {            if (i != n)                printf("%d ", ans[i]);            else                printf("%d\n", ans[i]);        }    }    return 0;}
0 0
原创粉丝点击