第11周项目2

来源:互联网 发布:java重写hashcode方法 编辑:程序博客网 时间:2024/06/06 08:55
  1. /*  
  2. 烟台大学计算机学院  
  3.   
  4. 文件名称:xiangmu.cpp  
  5.   
  6. 作者:常路  
  7.   
  8. 完成日期:2017年11月12日  
  9.   
  10. 问题描述:假设图G采用邻接表存储,分别设计实现以下要求的算法:  
  11.   (1)输出出图G中每个顶点的出度;  
  12.   (2)求出图G中出度最大的一个顶点,输出该顶点编号;  
  13.   (3)计算图G中出度为0的顶点数;  
  14.   (4)判断图G中是否存在边<i,j> 
  15.   
  16. 输入描述:无 
  17.   
  18. 输出描述:输出验证结果 
  19.  
  20. 用到了算法库graph.h 
  21.   
  22. */   
  23.   
  24.   
  25.   
  26. #include <stdio.h>  
  27. #include <malloc.h>  
  28. #include "../graph.h"  
  29.   
  30. //返回图G中编号为v的顶点的出度  
  31. int OutDegree(ALGraph *G,int v)  
  32. {  
  33.     ArcNode *p;  
  34.     int n=0;  
  35.     p=G->adjlist[v].firstarc;  
  36.     while (p!=NULL)  
  37.     {  
  38.         n++;  
  39.         p=p->nextarc;  
  40.     }  
  41.     return n;  
  42. }  
  43.   
  44. //输出图G中每个顶点的出度  
  45. void OutDs(ALGraph *G)  
  46. {  
  47.     int i;  
  48.     for (i=0; i<G->n; i++)  
  49.         printf("  顶点%d:%d\n",i,OutDegree(G,i));  
  50. }  
  51.   
  52. //输出图G中出度最大的一个顶点  
  53. void OutMaxDs(ALGraph *G)  
  54. {  
  55.     int maxv=0,maxds=0,i,x;  
  56.     for (i=0; i<G->n; i++)  
  57.     {  
  58.         x=OutDegree(G,i);  
  59.         if (x>maxds)  
  60.         {  
  61.             maxds=x;  
  62.             maxv=i;  
  63.         }  
  64.     }  
  65.     printf("顶点%d,出度=%d\n",maxv,maxds);  
  66. }  
  67. //输出图G中出度为0的顶点数  
  68. void ZeroDs(ALGraph *G)  
  69. {  
  70.     int i,x;  
  71.     for (i=0; i<G->n; i++)  
  72.     {  
  73.         x=OutDegree(G,i);  
  74.         if (x==0)  
  75.             printf("%2d",i);  
  76.     }  
  77.     printf("\n");  
  78. }  
  79.   
  80. //返回图G中是否存在边<i,j>  
  81. bool Arc(ALGraph *G, int i,int j)  
  82. {  
  83.     ArcNode *p;  
  84.     bool found = false;  
  85.     p=G->adjlist[i].firstarc;  
  86.     while (p!=NULL)  
  87.     {  
  88.         if(p->adjvex==j)  
  89.         {  
  90.             found = true;  
  91.             break;  
  92.         }  
  93.         p=p->nextarc;  
  94.     }  
  95.     return found;  
  96. }  
  97.   
  98. int main()  
  99. {  
  100.     ALGraph *G;  
  101.     int A[7][7]=  
  102.     {  
  103.         {0,1,1,1,0,0,0},  
  104.         {0,0,0,0,1,0,0},  
  105.         {0,0,0,0,1,1,0},  
  106.         {0,0,0,0,0,0,1},  
  107.         {0,0,0,0,0,0,0},  
  108.         {0,0,0,1,1,0,1},  
  109.         {0,1,0,0,0,0,0}  
  110.     };  
  111.     ArrayToList(A[0], 7, G);  
  112.     printf("(1)各顶点出度:\n");  
  113.     OutDs(G);  
  114.     printf("(2)最大出度的顶点信息:");  
  115.     OutMaxDs(G);  
  116.     printf("(3)出度为0的顶点:");  
  117.     ZeroDs(G);  
  118.     printf("(4)边<2,6>存在吗?");  
  119.     if(Arc(G,2,6))  
  120.         printf("是\n");  
  121.     else  
  122.         printf("否\n");  
  123.     printf("\n");  
  124.     return 0;  
  125. }  
原创粉丝点击