Think about it, this is one of the bare minimum spanning tree topics.
Here are two ways to calculate prim and kruscal
Of course, because the subject is a dense edge.
So actually the prim algorithm is a little bit better
Prim
1 /*2 minimum spanning tree, prim algorithm3 */4#include <cstdio>5#include <cstring>6#include <algorithm>7 8 using namespacestd;9 Const intN = the;Ten Const intINF =0x3f3f3f3f; One A intK, Fa[n], minn[n], first[n], vis[n];//Vis[n] Indicates whether to add to the saved collection - - structedge{ the inty, Next, D; - BOOL operator< (ConstEdge & M)Const{ - returnD <M.D; - } +}e[n*N]; - + voidAdd_edge (intXintYintd) A { atE[k].y = y, E[k].next = first[x], E[K].D =D; -FIRST[X] = k++; - } - - intPrimintSrcintN) - { inMEMSET (Minn,0x3f,sizeof(Minn)); -memset (Vis,0,sizeof(Vis)); toVIS[SRC] =1; + for(inti = first[src]; i!=-1; I=e[i].next) - { the intv =e[i].y; * if(!vis[v]) minn[v] =min (minn[v], e[i].d); $ }Panax Notoginseng intAns =0; - for(inti =1; I<n; i++) the { + intindex =0, Min =INF; A for(intj =1; J<=n; J + +) the { + if(Minn[j] <Min) { -Min =Minn[j]; $index =J; $ } - } -Ans + =Min; theMinn[index] =INF; -Vis[index] =1;//make index no longer accessibleWuyi //Update the for(intj = First[index]; j!=-1; j=e[j].next) - { Wu intv =e[j].y; - if(!vis[v]) minn[v] =min (minn[v], e[j].d); About } $ } - returnans; - } - A intMain () + { the //freopen ("a.in", "R", stdin); - intN, M, a, B, D; $ while(SCANF ("%d", &N), N) the { them = N (n1) /2; the for(inti =1; I<=n; i++) Fa[i] =i; the -K =0; inmemset (First,-1,sizeof(first)); the for(inti =0; I<m; i++){ thescanf"%d%d%d", &a, &b, &d); About Add_edge (A, B, d); the Add_edge (b, A, d); the } the +printf"%d\n", Prim (1, N)); - } the return 0;Bayi}
Kruscal:
1 /*2 minimum spanning tree, prim algorithm3 */4#include <cstdio>5#include <cstring>6#include <algorithm>7 8 using namespacestd;9 Const intN = the;Ten One intK, fa[n]; A - structedge{ - intx, y, D; the BOOL operator< (ConstEdge & M)Const{ - returnD <M.D; - } -}e[n*N]; + - voidAdd_edge (intXintYintd) + { Ae[k].x = x, e[k].y = y, e[k].d =D; atk++; - } - - intGet_head (intx) - { - while(x! = fa[x]) x=Fa[x]; in returnx; - } to + BOOLUnion (intXinty) - { the intfa_x =get_head (x); * intFa_y =Get_head (y); $ if(Fa_x! =fa_y) {Panax NotoginsengFa[fa_x] =fa_y; - return true; the } + return false; A } the + intMain () - { $ //freopen ("a.in", "R", stdin); $ intN, M, a, B, D; - while(SCANF ("%d", &N), N) - { theK =0; -m = N (n1) /2;Wuyi the for(inti =1; I<=n; i++) Fa[i] =i; - Wu for(inti =0; I<m; i++){ -scanf"%d%d%d", &a, &b, &d); About Add_edge (A, B, d); $ } -Sort (E, e+k); - intAns =0; - for(inti =0; i<k; i++){ A if(Union (e[i].x, e[i].y)) ans + =e[i].d; + } theprintf"%d\n", ans); - } $ return 0; the}
HDU 1233 or unblocked project (minimum spanning tree)