1. 程式人生 > >UVA 10305 —— Ordering Tasks(拓撲排序入門)

UVA 10305 —— Ordering Tasks(拓撲排序入門)

10305 - Ordering Tasks

Time limit: 3.000 seconds

Problem F

Ordering Tasks

Input: standard input

Output: standard output

Time Limit: 1 second

Memory Limit: 32 MB

John has n tasks to do. Unfortunately, thetasks are not independent and the execution of one task is only possible ifother tasks have already been executed.

Input

The input will consist of several instances of theproblem. Each instance begins with a line containing two integers, 1 <= n <=100 and mn is the number oftasks (numbered from 1 to n) and m is the number ofdirect precedence relations between tasks. After this, there will be m lines with twointegers i

 and j, representing thefact that task i must be executedbefore task j. An instance with n = m = 0 will finish theinput.

Output

For each instance,print a line with n integers representing the tasks in apossible 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<cstring>
#include<cstdio>
#include<cstdlib>
#define M 100+10
using namespace std;
struct pp{int v,w,next;}edge[M*2];int tot,root,head[M],n,m,c[M],topo[M],t;

inline void addedge(int u,int v,int w,int *h){edge[tot].v=v,edge[tot].w=w,edge[tot].next=h[u],h[u]=tot++;}

bool dfs(int u)
{
    c[u]=-1;  //標記為正在被訪問
    for(int i=head[u];i!=-1;i=edge[i].next){
        int v=edge[i].v;
        if(c[v]<0) return false; //再一次被訪問,說明是有環圖
        else if(!c[v]&&!dfs(v)) return false;
    }
    c[u]=1;topo[--t]=u;
    return true;
}


bool toposort()
{
    t=n;
    memset(c,0,sizeof c);
    for(int u=1;u<=n;++u){
        if(!c[u]){
            if(!dfs(u)) return false;
        }
    }
    return true;
}

int main()
{
    while(scanf("%d %d",&n,&m)&&(n||m)){
        int u,v;
        tot=0,memset(head,-1,sizeof head);
        while(m--){
            scanf("%d %d",&u,&v);
            addedge(u,v,0,head);
        }
        if(toposort());{
           for(int i=0;i<n;++i){
                printf("%d ",topo[i]);
            }
        }
        printf("\n");
    }
    return 0;
}