您的位置:首页 > 其它

UVA 10305 —— Ordering Tasks(拓扑排序入门)

2014-08-06 22:59 295 查看
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 m. n 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: