prim和Kruskal算法

prim算法

 1 #include <iostream>
 2 #include <cstdio>
 3 #define max 10
 4 using namespace std;
 5 typedef struct
 6 {
 7     int relation[max][max];
 8     int vertix[max];
 9     int Vnum,Rnum;
10 }MGraph;
11 
12 int getidx(MGraph *M,int v)
13 {
14     for(int i=0;i<M->Vnum;i++)
15     {
16         if(M->vertix[i]==v)
17             return i;
18     }
19     return -1;
20 }
21 void creat_DQWX(MGraph *M)
22 {
23     scanf("%d%d",&M->Vnum,&M->Rnum);
24     for(int i=0;i<M->Vnum;i++)
25     {
26         scanf("%d",&M->vertix[i]);
27     }
28     for(int i=0;i<M->Vnum;i++)
29     {
30         for(int j=0;j<M->Vnum;j++)
31         {
32             M->relation[i][j]=9999;
33         }
34     }
35     for(int i=0;i<M->Rnum;i++)
36     {
37         int v1,v2,w;
38         scanf("%d%d%d",&v1,&v2,&w);
39         int x1 = getidx(M,v1);
40         int x2 = getidx(M,v2);
41         M->relation[x1][x2]=w;
42         M->relation[x2][x1]=w;
43     }
44 }
45 typedef struct
46 {
47     int start;
48     int cost;
49 }closedge;
50 closedge theclose[max];
51 int mininum(MGraph *M,closedge close[])
52 {
53     int min = 99999;
54     int min_i = -1;
55     for(int i = 0;i<M->Vnum;i++)
56     {
57         if(close[i].cost>0 && close[i].cost<min)
58         {
59             min = close[i].cost;
60             min_i = i;
61         }
62     }
63     return min_i;
64 }
65 void prim(MGraph *M,int v)
66 {
67     int k = getidx(M,v);
68     for(int i=0;i<M->Vnum;i++)
69     {
70         if(i!=k)
71         {
72             theclose[i].start = k;
73             theclose[i].cost = M->relation[i][k];
74         }
75     }
76     theclose[k].cost=0;
77 
78     for(int i=1;i<M->Vnum;i++)
79     {
80         k = mininum(M,theclose);
81         printf("%d->%d cost:%d\n",M->vertix[theclose[k].start],M->vertix[k],theclose[k].cost);
82         theclose[k].cost = 0;
83         for(int j=0;j<M->Vnum;j++)
84         {
85             if(M->relation[k][j]<theclose[j].cost)
86             {
87                 theclose[j].cost = M->relation[k][j];
88                 theclose[j].start = k;
89             }
90         }
91     }
92 }
93 int main()
94 {
95     MGraph M;
96     creat_DQWX(&M);
97     prim(&M,3);
98 }

 

posted @ 2018-12-08 11:04  谋莽台  阅读(148)  评论(0编辑  收藏  举报