UVa 10305 - Ordering Tasks , 经典的拓扑排序

UVA 10305 拓扑排序解析
本文详细解析了UVA 10305题目的拓扑排序算法实现,介绍了两种常见方法:一种是基于邻接表的贪心算法,另一种是基于深度优先搜索的算法,并提供了完整的代码示例。

FILE10305-Ordering Tasks10119
46.70%
3784
91.94%
题目链接:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105&page=show_problem&problem=1246


题目:


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 <= 100andm.nis the number of tasks (numbered from1ton) andmis the number of direct precedence relations between tasks. After this, there will bemlines with two integersiandj, representing the fact that taskimust be executed before taskj. An instance withn = m = 0will finish the input.


Output

For each instance, print a line withnintegers 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个任务要做, 不幸的是,这些任务并不是独立的,执行某个任务之前要先执行完其他相关联的任务。



分析与总结:

这题是最基础的拓扑排序。

拓扑排序的定义:对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若<u,v> ∈E(G),则u在线性序列中出现在v之前。


以上的定义比较“学术“,简单的说,就是一些事件,某些必须在另外某些发生之前; 比如穿袜和穿鞋;再比如大学选课,选修某门课的前提必须先修完其他一些相关连的课程才可以。


所以,拓扑排序在现实生活中有着十分广泛的应用。


这里有一个拓扑排序过程的演示动画,十分直观:


一般的题目可能会给一些事件,和一些发生次序,来求一个拓扑排序;



对于拓扑排序 主要有两种方法。

第一种是贪心的思路, 以邻接表为图的存储结构,过程直接模拟上面的演示动画:

a)扫描顶点表,将入度为零的顶点入栈; (ps:这里栈可以使优先队列 and so on。。)

b)当栈非空时:

输出栈顶元素v,出栈;

检查v的出边,将每条出边的终端顶点的入度减1,若该顶点入度为0,入栈;

c)当栈空时,若输出的顶点小于顶点数,则说明AOV网有回路,否则拓扑排序完成。



下面是给出这种方法的解题代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int G[110][110],n,m,a,b;
int vis[110],c[110], topo[110], cnt[110];
void topoSort(){
    int count=0;
    while(count < n){ 
        for(int i=1; i<=n; ++i) if(!cnt[i]){ // 如果是入度为0的
            --cnt[i];  
            topo[count++] = i;
            for(int j=1; j<=n; ++j){
                if(i!=j && G[i][j]){
                    G[i][j] = 0;
                    --cnt[j];
                }
            }
        }
    }
}
int main(){
#ifdef LOCAL
    freopen("input.txt","r",stdin);
#endif
    while(~scanf("%d %d",&n,&m) && n+m){
        memset(G, 0, sizeof(G));
        memset(cnt, 0, sizeof(cnt));
        for(int i=0; i<m; ++i){
            scanf("%d %d",&a,&b);
            G[a][b] = 1;
            ++cnt[b];  // 记录入度数量
        }
        if(topoSort()) {
            printf("%d",topo[0]);
            for(int i=1; i<n; ++i)
                printf(" %d",topo[i]);
            printf("\n");
        }
    }
    return 0;
}



第二种方法是《算法导论》上的, 刘汝佳的《算法入门经典》P 111页上介绍的也是这种方法。
这种方法是用dfs,从根节点开始深搜,每搜到一点记录下来开始搜索和结束搜索的时间戳;

然后根据结束时间从大到小排序即可。这种方法时间效率更高,更推荐。


推荐的解法:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int G[110][110],n,m,a,b;
int vis[110],c[110], topo[110], t;

bool dfs(int u){
    vis[u] = -1; //表示正在访问 
    for(int v=1; v<=n; ++v) if(G[u][v]){
        if(vis[v] == -1) return false; // 如果存在有向环,失败退出
        else if(!vis[v] && !dfs(v)) return false;
    }
    // 结束访问
    vis[u] = 1; topo[--t] = u;
    return true;
}

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

int main(){
#ifdef LOCAL
    freopen("input.txt","r",stdin);
#endif 
    // 注意输入那里的结束条件不能是 n&&m,因为m可能是0
    while(~scanf("%d %d",&n,&m) && n+m){
        memset(G, 0, sizeof(G));
        for(int i=0; i<m; ++i){
            scanf("%d %d",&a,&b);
            G[a][b] = 1;
        }
        if(topoSort()) {
            printf("%d",topo[0]);
            for(int i=1; i<n; ++i)
                printf(" %d",topo[i]);
            printf("\n");
        }
    }
    return 0;
}



### Pytest-ordering 插件概述 Pytest-ordering 是一个用于控制测试用例执行顺序的插件。该插件允许开发者通过简单的装饰器定义不同测试之间的相对顺序。 ### 安装方法 为了安装 pytest-ordering 插件,在终端中可以使用 `pip` 工具并运行如下命令: ```bash pip install pytest-ordering ``` 对于另一个类似的库 pytest-order,也可以采用相似的方式进行安装[^2]。 ### 使用教程 #### 控制测试用例执行顺序的方法 pytest-ordering 提供了几种不同的方式来设置测试用例的执行顺序。最常见的是利用带有参数的 `@pytest.mark.run()` 装饰器,其中 `order` 参数决定了具体的排列位置;数值越低表示优先级越高,意味着更早被执行。例如: ```python import pytest @pytest.mark.run(order=1) def test_first(): assert True, "This should run first" @pytest.mark.run(order=2) def test_second(): assert True, "This will follow the previous one" ``` 除了显式的数字排序外,还存在一些特殊的标记用来简化某些特定情况下的操作,比如让某个测试总是位于队列开头或结尾。不过需要注意的是,部分早期版本中存在的标签如 `first` 和 `last` 在较新的发行版里已被移除不再推荐使用[^4]。 #### 示例代码展示如何应用这些特性 下面给出了一组完整的例子说明怎样运用上述提到的功能点: ```python import pytest # 设置此测试最先执行 @pytest.mark.run(order=-2) def test_negative_order_example(): print("\nTest with negative order value.") pass # 正常按序号指定先后关系 @pytest.mark.run(order=1) def test_positive_order_one(): print("\nFirst ordered positive number.") pass @pytest.mark.run(order=3) def test_larger_than_default(): print("\nLargest defined position.") pass # 默认情况下未指明次序则放在最后处理 def test_without_explicit_order(): print("\nNo explicit ordering applied here.") pass # 小于零会被安排到非常靠前的位置 @pytest.mark.run(order=-1) def test_most_prioritized(): print("\nMost prioritized due to smallest integer used as its parameter.") pass ``` 当这段脚本被 pytest 执行时,输出会按照设定好的序列依次打印出来,从而验证了各个测试案例确实依照预期进行了编排。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值