zoukankan      html  css  js  c++  java
  • 图——拓扑排序(uva10305)

    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 ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will finish 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

    题意:就是给你几组任务,给出了任务的先后顺序,求出他们的执行顺序

    拓扑排序就是用来解决这类排序问题的... 先构造出一个图,用dfs递归实现来遍历

    自己敲的时候,wa了n次...然后Baidu了一下,发现自己的错误和网友的错误惊人的相似(QAQ),判断m n是否为0的时候应该用 m||n 来确定两个都为0而不是 m&&n !!

    #include<iostream>
    #include<string.h>
    #include<cstdio>
    using namespace std;
    const int maxn = 1000 + 5;
    
    int a[maxn][maxn];
    int c[maxn];
    int topo[maxn];
    int n, m, t;
    
    bool dfs(int u){
        c[u] = -1;
        for(int v=1; v<=n; v++){
            if(a[u][v]){
                if(c[v] < 0) return false;
                else if(!c[v] && !dfs(v)) return false;
            }
        }
        c[u] = 1;
        topo[--t] = u;
        return true;
    }
    bool topo_sort(){
        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(){
        int j, k;
        while(scanf("%d %d", &n, &m) == 2 && (n || m )){
            memset(a, 0, sizeof(a));
            for(int i=0; i<m; i++){
                cin >> j >> k;
                a[j][k] = 1;
            }
            if(topo_sort()){
                for(int i=0; i<n; i++){
                    if(i == 0) cout << topo[i];
                    else cout << " " << topo[i];
                }
                cout << endl;    
            }
            else
                cout << "No" << endl;
    
        }
    
        
        return 0;
    }
  • 相关阅读:
    C# 编码约定
    SQL 合并多列为一行字符串
    Flex 粒子效果
    安装flashplayer 提示 "您尝试安装的 Adobe Flash Player" 版本不是最新版本. 请访问 Player 下载中心 获取最新、最安全版本"的解决方法
    Flex Builder 好用的插件
    【默认】博客正式开通
    Vulkanished2021重要内容简介
    论文读书笔记8
    论文读书笔记5
    论文读书笔记2
  • 原文地址:https://www.cnblogs.com/ledoc/p/6224272.html
Copyright © 2011-2022 走看看