UVa 10305 Ordering Tasks 拓扑排序 解题报告

Problem Description

John has n tasks to do. Unfortunately, thetasks are not independent and the execution of one task is

only possible if other tasks have alreadybeen executed.

Input

The input will consist of several instancesof 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 isthe

number of direct precedence relations betweentasks. After this, there will be m lines with two integers

i and j, representing the fact that task imust be executed before task j.

An instance with n = m = 0 will finish theinput. 

Output

For each instance, print a line with nintegers 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


分析:

题意:假设有n个变量,还有m个二元组(u,v),分别表示变量u小于v。那么,所有变量从小到大排列起来应该是什么样子的呢?

把每个变量看成一个点,“小于”关系看成有向边,则得到了一个有向图。这样,我们的任务实际上是把一个图的所有结点排序,使得每一条有向边(u,v)对应的u都排在v的前面。

用dfs完成拓扑排序,在访问完一个结点之后吧它加到当前拓扑序的首部。

#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
#include<math.h>  
#define max 100+5  
int c[max],topo[max],t,n,G[max][max];  
int dfs(int u)  
{  
    int v;  
    c[u] = -1;  //访问标志,-1为正在访问,0是未访问,1是已经访问
    for(v = 1; v <= n; v++)  
        if(G[u][v])  
        {  
            if(c[v] < 0) return 0;  
            else if(!c[v] && !dfs(v)) return 0;  
        }  
    c[u] = 1;  
    topo[--t] = u;  
    return 1;  
}  
int toposort()  
{  
    int i;  
    t = n;  
    memset(c,0,sizeof(c));  
    for(i = 1; i <= n; i++)  
        if(!c[i] && !dfs(i))  return 0;  
    return  1;  
}  
int main()  
{  
    int m,i;  
    while(scanf("%d%d",&n,&m),n || m)  
    {  
        int u,v;  
        memset(G,0,sizeof(G));  
        for(i = 0 ; i < m ; i++)  
        {  
            scanf("%d%d",&u,&v);  
            G[u][v] = 1;  
        }  
        if(toposort())  
        {  
            for(i = 0; i < n-1; i++)  
                printf("%d ",topo[i]);  
            printf("%d\n",topo[i]);  
        }  
    }  
    return 0;  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值