zoukankan      html  css  js  c++  java
  • 拓扑排序示例程序

    输入:顶点个数n,边数m,然后是m行,表示每条边的起点和终点u, v 表示从顶点u到顶点v的一条有向边。输入0 0 表示结束。

    输出:如果不存在有向环,则输出一个拓扑有序序列;否则,输出“Netword has a cycle!”

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstdlib>
     4 #include <cstring>
     5 #include <cctype>
     6 #include <stack>
     7 #include <queue>
     8 #include <map>
     9 #include <set>
    10 #include <vector>
    11 #include <cmath>
    12 #include <algorithm>
    13 #define lson l, m, rt<<1
    14 #define rson m+1, r, rt<<1|1
    15 using namespace std;
    16 typedef long long int LL;
    17 const int MAXN =  0x3f3f3f3f;
    18 const int  MIN =  -0x3f3f3f3f;
    19 const double eps = 1e-9;
    20 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
    21   {1,1},{1,-1},{-1,-1}};
    22 int n, m, Count[100], i, j, top, out[100];
    23 struct ArcNode{
    24   int to; struct ArcNode *next;
    25 };
    26 ArcNode *List[100];
    27 void topsort()
    28 {
    29   ArcNode *temp; top = -1; int k, len = 0; bool flag = true;
    30   for (i = 0; i < n; ++i) {
    31     if (Count[i] == 0) {
    32       Count[i] = top; top = i;
    33     }
    34   }
    35   for (i = 0; i < n; ++i) {
    36     k = top; if (k == -1) { flag = false; break; }
    37     top = Count[k]; temp = List[k]; out[len++] = k + 1;
    38     while (temp != NULL) {
    39       Count[temp->to]--;
    40       if (Count[temp->to] == 0) {
    41         Count[temp->to] = top; top = temp->to;
    42       } temp = temp->next;
    43     }
    44   }
    45   if (flag) {
    46     for (i = 0; i < len; ++i) {
    47       if (!i) printf("%d", out[i]); else printf(" %d", out[i]);
    48     } printf("\n");
    49   } else printf("Network has a cycle!\n");
    50   for (i = 0; i < n; ++i) {
    51     temp = List[i];
    52     while (temp) {
    53       List[i] = temp->next; delete temp; temp = List[i];
    54     }
    55   }
    56 }
    57 int main(void){
    58 #ifndef ONLINE_JUDGE
    59   freopen("topsort.in", "r", stdin);
    60 #endif
    61   while (~scanf("%d%d", &n, &m)){
    62     if (m + n == 0) break;
    63     int u, v; ArcNode *temp;
    64     memset(Count, 0, sizeof(Count));
    65     memset(List, 0, sizeof(List));
    66     memset(out, 0, sizeof(out));
    67     for (i = 0; i < m; ++i){
    68       scanf("%d%d", &u, &v); u--; v--;
    69       temp = new ArcNode; temp->next = NULL; temp->to = v;
    70       temp->next = List[u]; List[u] = temp; Count[v]++;
    71     }
    72     topsort();
    73   }
    74 
    75   return 0;
    76 }

    用数组实现的链式栈 ,好神奇……

  • 相关阅读:
    vue-cli(vue脚手架)简单流程
    windows环境之node.js安装与环境配置
    fiddler的下载和简单使用
    Linux 配置nginx 代理tomcat,配置ssl
    来聊一聊导出数据问题
    作为一个开发人员应该具备怎么样技术栈和职业素养
    NODEJS的误打误撞
    聊一下程序员的日常
    openstack安装部署私有云详细图文
    openstack:OpenStack架构详解,
  • 原文地址:https://www.cnblogs.com/liuxueyang/p/3048369.html
Copyright © 2011-2022 走看看