第十三周项目5-拓扑排序算法验证

来源:互联网 发布:淘库网络关先生 编辑:程序博客网 时间:2024/05/17 06:33

问题:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /*  
  2. * Copyright (c)2016,烟台大学计算机与控制工程学院  
  3. * All rights reserved.  
  4. * 文件名称:项目5.cbp  
  5. * 作    者:陈晓琳  
  6. * 完成日期:2016年11月24日  
  7. * 版 本 号:v1.0  
  8.   
  9. * 问题描述:拓扑排序算法的验证  
  10.   
  11. * 输入描述:无  
  12. * 程序输出:测试数据  
  13. */    
头文件及功能函数见【图算法库】

测试用图:

代码:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include "graph.h"    
  2.     
  3.     
  4. void TopSort(ALGraph *G)    
  5. {    
  6.     int i,j;    
  7.     int St[MAXV],top=-1;            //栈St的指针为top    
  8.     ArcNode *p;    
  9.     for (i=0; i<G->n; i++)          //入度置初值0    
  10.         G->adjlist[i].count=0;    
  11.     for (i=0; i<G->n; i++)          //求所有顶点的入度    
  12.     {    
  13.         p=G->adjlist[i].firstarc;    
  14.         while (p!=NULL)    
  15.         {    
  16.             G->adjlist[p->adjvex].count++;    
  17.             p=p->nextarc;    
  18.         }    
  19.     }    
  20.     for (i=0; i<G->n; i++)    
  21.         if (G->adjlist[i].count==0)  //入度为0的顶点进栈    
  22.         {    
  23.             top++;    
  24.             St[top]=i;    
  25.         }    
  26.     while (top>-1)                  //栈不为空时循环    
  27.     {    
  28.         i=St[top];    
  29.         top--;              //出栈    
  30.         printf("%d ",i);            //输出顶点    
  31.         p=G->adjlist[i].firstarc;   //找第一个相邻顶点    
  32.         while (p!=NULL)    
  33.         {    
  34.             j=p->adjvex;    
  35.             G->adjlist[j].count--;    
  36.             if (G->adjlist[j].count==0)//入度为0的相邻顶点进栈    
  37.             {    
  38.                 top++;    
  39.                 St[top]=j;    
  40.             }    
  41.             p=p->nextarc;       //找下一个相邻顶点    
  42.         }    
  43.     }    
  44. }    
  45.     
  46.     
  47. int main()    
  48. {    
  49.     ALGraph *G;    
  50.     int A[10][10]=    
  51.     {    
  52.         {0,0,0,1,1,0,0,0,0,1},    
  53.         {0,0,1,1,0,0,0,1,0,0},    
  54.         {0,0,0,0,1,1,0,0,1,0},    
  55.         {0,0,0,0,0,0,1,0,0,0},    
  56.         {0,0,0,0,0,0,0,1,0,0},    
  57.         {0,0,0,0,1,0,0,0,0,0},    
  58.         {0,0,0,0,0,0,0,0,0,0},    
  59.         {0,0,0,0,0,0,1,0,0,0},    
  60.         {0,0,0,0,0,0,0,0,0,1},    
  61.         {0,0,0,0,0,0,0,0,0,0}    
  62.     };    
  63.     ArrayToList(A[0], 10, G);    
  64.     DispAdj(G);    
  65.     printf("\n");    
  66.     printf("拓扑序列:");    
  67.     TopSort(G);    
  68.     printf("\n");    
  69.     return 0;    
  70. }    
运行结果:


知识点总结:

拓扑排序算法的验证。

0 0
原创粉丝点击