1. 程式人生 > >圖的順序儲存結構

圖的順序儲存結構

  1 #include <iostream>
  2 #define max 100
  3 #include <cstdio>
  4 using namespace std;
  5 typedef enum
  6 {
  7     YX,WX,DQYX,DQWX
  8 }Type;
  9 typedef struct
 10 {
 11     int rel;
 12     int *info;
 13 }AdjMatrix[max][max];
 14 typedef struct
 15 {
 16     int vertex[max];    //
頂點 17 AdjMatrix relation; //頂點之間的關係 18 Type type; //型別 19 int V,R; 20 }MGraph; 21 int LocateV(MGraph *M,int v) 22 { 23 for(int i=0;i<M->V;i++) 24 { 25 if(M->vertex[i]==v) 26 return i; 27 } 28 return -1; 29 }
30 //構造有向圖 31 void CreatYX(MGraph *M) 32 { 33 scanf("%d%d",&M->V,&M->R); 34 for(int i=0;i<M->V;i++) 35 { 36 scanf("%d",&M->vertex[i]); 37 } 38 for(int i=0;i<M->V;i++) 39 { 40 for(int j=0;j<M->V;j++) 41 {
42 M->relation[i][j].rel=0; 43 M->relation[i][j].info=NULL; 44 } 45 } 46 for(int i=0;i<M->R;i++) 47 { 48 int v1,v2; 49 scanf("%d%d",&v1,&v2); 50 int x = LocateV(M,v1); 51 int y = LocateV(M,v2); 52 M->relation[x][y].rel = 1; 53 } 54 } 55 //構造無向圖 56 void CreatWX(MGraph *M) 57 { 58 scanf("%d%d",&M->V,&M->R); 59 for(int i=0;i<M->V;i++) 60 { 61 scanf("%d",&M->V); 62 } 63 for(int i=0;i<M->V;i++) 64 { 65 for(int j=0;j<M->V;j++) 66 { 67 M->relation[i][j].info=NULL; 68 M->relation[i][j].rel=0; 69 } 70 } 71 for(int i=0;i<M->R;i++) 72 { 73 int v1,v2; 74 scanf("%d%d",&v1,&v2); 75 int x = LocateV(M,v1); 76 int y = LocateV(M,v2); 77 M->relation[x][y].rel = 1; 78 M->relation[y][x].rel = 1; 79 } 80 } 81 //構造帶權有向圖 82 void CreatDQYX(MGraph *M) 83 { 84 scanf("%d%d",&M->V,&M->R); 85 for(int i=0;i<M->V;i++) 86 { 87 scanf("%d",&M->vertex[i]); 88 } 89 for(int i=0;i<M->V;i++) 90 { 91 for(int j=0;j<M->V;j++) 92 { 93 M->relation[i][j].rel=0; 94 M->relation[i][j].info=NULL; 95 } 96 } 97 for(int i=0;i<M->R;i++) 98 { 99 int v1,v2,w; 100 scanf("%d%d",&v1,&v2,&w); 101 int x = LocateV(M,v1); 102 int y = LocateV(M,v2); 103 M->relation[x][y].rel = w; 104 } 105 } 106 //構造帶權無向圖 107 void CreatDQWX(MGraph *M) 108 { 109 scanf("%d%d",&M->V,&M->R); 110 for(int i=0;i<M->V;i++) 111 { 112 scanf("%d",&M->V); 113 } 114 for(int i=0;i<M->V;i++) 115 { 116 for(int j=0;j<M->V;j++) 117 { 118 M->relation[i][j].info=NULL; 119 M->relation[i][j].rel=0; 120 } 121 } 122 for(int i=0;i<M->R;i++) 123 { 124 int v1,v2,w; 125 scanf("%d%d",&v1,&v2,&w); 126 int x = LocateV(M,v1); 127 int y = LocateV(M,v2); 128 M->relation[x][y].rel = w; 129 M->relation[y][x].rel = w; 130 } 131 } 132 void CreatGraph(MGraph *M) 133 { 134 scanf("%d",&M->type); 135 switch(M->type) 136 { 137 case YX: 138 return CreatYX(M); 139 break; 140 case WX: 141 return CreatWX(M); 142 break; 143 case DQWX: 144 return CreatDQWX(M); 145 break; 146 case DQYX: 147 return CreatDQYX(M); 148 break; 149 } 150 } 151 void print(MGraph M) 152 { 153 for(int i=0;i<M.V;i++) 154 { 155 for(int j=0;j<M.V;j++) 156 { 157 printf("%d ",M.relation[i][j].rel); 158 } 159 printf("\n"); 160 } 161 } 162 int main() 163 { 164 MGraph M; 165 CreatGraph(&M); 166 print(M); 167 }