• 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 }
  • 相关阅读:
    .NET平台下Web树形结构程序设计李洪根
    [总结]Asp.net中的页面乱码的问题
    [原创]Datagrid中绑定DropDownList的例子
    [原创]TreeView的递归问题!FAQ
    [个人]我所有的Email地址!
    心情随笔(一)
    [原创]用JS做的一个打字程序(为网友qixiao)
    [转贴]一个通用的数据分页的存储过程
    [转贴]怎么样写一个XML文件到客户端
    [原创]用JS给DropDownList添加新项!
  • 原文地址:https://www.cnblogs.com/doubleshik/p/3440283.html
Copyright © 2020-2023  润新知