UVA - 10305 - Ordering Tasks(拓扑排序)

来源:互联网 发布:ncbi下载基因组数据 编辑:程序博客网 时间:2024/06/15 18:18

UVA - 10305 - Ordering Tasks(拓扑排序)

Time Limit: 1 second      Memory Limit: 32 MB

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<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;int n, m;const int maxn = 110;int mp[maxn][maxn], indegree[maxn], ans[maxn];queue<int> q;void topologic(){    int cnt = 0;    for (int i = 1; i <= n; i++){        if (indegree[i] == 0)            q.push(i);         //把所有入度为0的点压入队中    }    while (!q.empty()){        int now = q.front();        q.pop();        ans[cnt++] = now;        for (int i = 1; i <= n; i++){            int a = mp[now][i];            if(mp[now][i]!=0){                indegree[i]--;                if(indegree[i] == 0)                    q.push(i);        //把所有入度为0的点压入队中             }        }    }    printf("%d", ans[0]);    for(int i = 1; i < cnt; i++)        printf(" %d", ans[i]);    printf("\n");}int main(){    while(scanf("%d %d", &n, &m)!=EOF){        if(!n && !m)            break;        memset(mp, 0, sizeof(mp));        memset(indegree, 0, sizeof(indegree));        for(int i = 0; i < m; i++){            int a, b;            scanf("%d %d", &a, &b);            mp[a][b] = 1;            indegree[b]++;        }        topologic();    }    return 0;}
0 0