zoukankan      html  css  js  c++  java
  • uva10305

    典型拓扑排序 记录个模板

    题目:

    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, 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

    代码:
     1 #include <iostream>
     2 #include <memory.h>
     3 using namespace std;
     4 const int maxn = 200;
     5 
     6 int G[maxn][maxn];
     7 int n,m,t;
     8 int Status[maxn];       //1表示访问过 0表示没访问 -1 表示表示正在访问
     9 int topo[maxn];
    10 bool dfs(int u)
    11 {
    12     Status[u]=-1;
    13 
    14     for(int i=1;i<=n;i++)
    15     {
    16         if(G[u][i])
    17         {
    18             if(Status[i]<0)return false;
    19             else if(!Status[i]&&!dfs(i))return false;
    20         }
    21     }
    22 
    23     topo[t--]=u;
    24     Status[u]=1;
    25     return true;
    26 
    27 }
    28 bool toposort()
    29 {
    30     t=n;
    31     memset(Status,0,sizeof(Status));
    32 
    33     for(int i=1;i<=n;i++)
    34     {
    35         if(!Status[i])
    36         {
    37             if(!dfs(i))return false;
    38         }
    39     }
    40     return true;
    41 
    42 }
    43 
    44 
    45 int main()
    46 {
    47 
    48     while(cin>>n>>m)
    49     {
    50         if(n+m==0)break;
    51 
    52         int p,q;
    53         for(int i=0;i<m;i++)
    54         {
    55             cin>>p>>q;
    56             G[p][q]=1;
    57         }
    58         toposort();
    59         for(int i=1;i<n;i++)
    60         {
    61             cout<<topo[i]<<" ";
    62         }
    63         cout<<topo[n]<<endl;
    64         memset(G,0,sizeof(G));
    65         memset(topo,0,sizeof(topo));
    66         memset(Status,0,sizeof(Status));
    67 
    68     }
    69 
    70     return 0;
    71 }
  • 相关阅读:
    常见排序算法基于JS的实现
    PubSub的一种实现
    小结JS中的OOP(下)
    自己的一个LESS工具函数库
    小结JS中的OOP(中)
    小结JS中的OOP(上)
    表单的常用操作
    动手写插件之日历插件
    数组排序,字符串math,replace练习
    C++ Const(常类型)的作用总结
  • 原文地址:https://www.cnblogs.com/doubleshik/p/3440283.html
Copyright © 2011-2022 走看看