UVA - 10305 Ordering Tasks

来源:互联网 发布:石大在线网络教育 编辑:程序博客网 时间:2024/05/01 08:27

Problem F

Ordering Tasks

Input: standardinput

Output: standardoutput

Time Limit: 1 second

Memory Limit: 32MB

 

John has n tasks to do.Unfortunately, the tasks are not independent and the execution of one task is onlypossible if other tasks have already been executed.

Input

The input will consist of several instances ofthe problem. Each instance begins with a line containing two integers,1 <= n <= 100 and m. nis the number of tasks (numbered from1to n) and m is the number of direct precedence relations between tasks. Afterthis, there will bem lines with twointegers i and j, representing the fact that taski must be executed before task j.An instance withn = m = 0 willfinish 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 <iostream>#include <cstdio>#include <queue>#include <cstring>#define N 101using namespace std;int n, m, k;int vis[N],b[N];int a[N][N];void prin() {queue<int> q;for (int i = 1; i <= n; i++) if (b[i] == 0)q.push(i);while (!q.empty()) {int t = q.front();q.pop();k++;if (k == n)printf("%d\n",t);elseprintf("%d ",t);for (int i = 1; i <= n; i++) if (a[t][i] && vis[i] == 0) {b[i]--;if (b[i] == 0) {vis[i] = 1;q.push(i);}}}}int main() {while (scanf("%d%d",&n,&m) != EOF) {if (n == 0 && m == 0) break;k = 0;memset(vis,0,sizeof(vis));memset(b,0,sizeof(b));memset(a,0,sizeof(a));for (int i = 0; i < m; i++) {int u, v;scanf("%d%d",&u,&v);a[u][v]++;b[v]++;} prin();}return 0;}

方法二:


#include<stdio.h>#include<string.h>int n,st[110],top,G[110][110],vis[110];void dfs(int u){    int v;    vis[u]=1;    for(v=1;v<=n;v++)        if(G[u][v]&&!vis[v])            dfs(v);    st[--top]=u;}int main(){    int i,j,k,m,a,b;    while(1)    {        scanf("%d%d",&n,&m);        if(n==0)            break;        memset(G,0,sizeof(G));        for(i=0;i<m;i++)        {            scanf("%d%d",&a,&b);            G[a][b]=1;        }        memset(vis,0,sizeof(vis));        top=n;        for(i=1;i<=n;i++)            if(!vis[i])                dfs(i);        for(i=0;i<n;i++)        {            if(i)                printf(" ");            printf("%d",st[i]);        }        printf("\n");    }    return 0;    }


0 0