• 基于邻接矩阵的拓扑排序


    总结下算法好了:

    (1)构图:每个活动是一个顶点,如果A必须排在B前面,那么有边从顶点A指向顶点B,顶点B的入度+1

    (2)遍历所有顶点,将入度为0的顶点入栈

    (3)如果栈不为空,则将栈顶出栈,然后将该顶点从图中删掉,即该点指向的点的入度-1,如果减后为0则入栈,重复(3)

    简单版的代码,只能举出一种拓扑排序:

     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 #define MAX_VERTEX_NUM 100
     5 
     6 int ver_num;
     7 char vertex[MAX_VERTEX_NUM];
     8 int indeg[MAX_VERTEX_NUM];
     9 int graph[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
    10 
    11 void CreateMGragh()
    12 {
    13     int i,j;
    14     int n1,n2,f1,f2;
    15     char ch1,ch2,ch3;
    16     while(1){
    17         scanf("%c%c%c",&ch1,&ch2,&ch3);
    18         f1 = f2 = 0;
    19         for (i=0; vertex[i] != 0; i++){
    20             if (vertex[i] == ch1){
    21                 f1 = 1;
    22                 n1 = i;
    23                 break;
    24             }
    25         }
    26         if (f1 == 0){
    27             vertex[i] = ch1;
    28             n1 = i;
    29         }
    30         for (j=0; vertex[j] != 0; j++){
    31             if (vertex[j] == ch2){
    32                 f2 = 1;
    33                 n2 = j;
    34                 break;
    35             }
    36         }
    37         if (f2 == 0){
    38             vertex[j] = ch2;
    39             n2 = j;
    40         }
    41 
    42         graph[n1][n2] = 1;
    43         indeg[n2]++;
    44 
    45 
    46         if (ch3 == '
    '){
    47             break;
    48         }
    49     }
    50     for (i=0; vertex[i] != 0; i++);
    51     ver_num = i;
    52 }
    53 
    54 void topsort()
    55 {
    56     int stack[MAX_VERTEX_NUM];
    57     int i,top;
    58 
    59     top = 0;
    60     memset(stack,0,sizeof(stack));
    61     
    62     // 入度为0的点都入栈
    63     for (i=0; i<ver_num; i++){
    64         if (indeg[i] == 0){
    65             stack[top++] = i;
    66         }
    67     }
    68 
    69     while(0 != top){
    70         // 出栈
    71         printf("%c",vertex[stack[--top]]);
    72         
    73         // 把这个点删掉 即它后面的点的入度-1 并把连线去掉
    74         for (i=0; i<ver_num; i++){
    75             if (graph[stack[top]][i] == 1){
    76                 graph[stack[top]][i] = 0;
    77                 indeg[i]--;
    78                 if (indeg[i] == 0){
    79                     stack[top++] = i;
    80                 }
    81             }
    82         }
    83     }
    84     printf("
    ");
    85 }
    86 
    87 int main()
    88 {
    89     CreateMGragh();
    90     topsort();
    91     return 0;
    92 }

    测试用例及结果:

  • 相关阅读:
    ABB机器人 带参数例行程序
    面试题10- I:斐波那契数列(C++)
    面试题39:数组中出现次数超过一半的数字(C++)
    面试题50:第一个只出现一次的字符(C++)
    第八部分 表的基本操作
    第七部分 表中数据的基本操作
    面试题18:删除链表的节点(C++)
    面试题35:复杂链表的复制(C++)
    面试题54:二叉搜索树的第k大节点(C++)
    面试题62:圆圈中最后剩下的数字(C++)
  • 原文地址:https://www.cnblogs.com/raul-ac/p/3271501.html
Copyright © 2020-2023  润新知