D.N village, N (n-1)/2 road, paved several roads, so that any two villages can reach. The minimum total length of the road.
S. Minimum spanning tree
C.prim algorithm: Cost[a][b] and Cost[b][a] are all assigned values.
/*the prim algorithm prim the MST consumption matrix cost[][], the label starts at 0, 0~N-1 returns the weight of the smallest spanning tree, and 1 indicates that the original is not connected*/#include<iostream>#include<stdio.h>#include<string.h>using namespacestd;Const intinf=0x3f3f3f3f;Const intmaxn= the;BOOLVIS[MAXN];intLOWC[MAXN];//dot is 0 n-1intPrim (intCOST[][MAXN],intN) { intans=0; memset (Vis,false,sizeof(VIS)); vis[0]=true; for(intI=1; i<n;i++) lowc[i]=cost[0][i]; for(intI=1; i<n;i++){ intMinc=INF; intp=-1; for(intj=0; j<n;j++) if(!vis[j]&&minc>Lowc[j]) {Minc=Lowc[j]; P=J; } if(Minc==inf)return-1;//The original is not connectedans+=Minc; VIS[P]=true; for(intj=0; j<n;j++) if(!vis[j]&&lowc[j]>Cost[p][j]) lowc[j]=Cost[p][j]; } returnans;}intMain () {intCOST[MAXN][MAXN]; intN; intu,v,w; while(~SCANF ("%d",&N)) { if(n==0) Break; for(intI=0; i<maxn;++i) { for(intj=0; j<maxn;++j) {Cost[i][j]=INF; } } intm=n* (n1)/2; for(intI=0; i<m;++i) {scanf ("%d%d%d",&u,&v,&W); --u;--W; COST[U][V]=cost[v][u]=W; } printf ("%d\n", Prim (cost,n)); } return 0;}
View Code
C2. Kruskal algorithm: Add A->b or b->a an edge.
/*Kruskal algorithm Kruskal algorithm to find MST*/#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespacestd;Const intmaxn= the;//maximum number of pointsConst intmaxm=10000;//maximum number of sidesintF[MAXN];//and check the set usestructedge{intU,v,w;} EDGE[MAXM];//Storage edge information, including start/end/Weight valuesintTol//number of edges, assigned 0 before adding edgevoidAddedge (intUintVintW) {edge[tol].u=u; EDGE[TOL].V=v; Edge[tol++].w=W;}//sort functions to sort edges from small to large by weightBOOLCMP (Edge A,edge b) {returna.w<B.W;}intFindintx) { if(f[x]==-1)returnx; Else returnf[x]=find (F[x]);}//incoming number, returns the minimum spanning tree weight, if not connected return-1intKruskal (intN) {memset (F,-1,sizeof(F)); Sort (Edge,edge+tol,cmp); intCnt=0;//calculate the number of joined edges intans=0; for(intI=0; i<tol;i++){ intu=edge[i].u; intv=edge[i].v; intw=EDGE[I].W; intt1=find (U); intT2=Find (v); if(t1!=T2) {ans+=W; F[T1]=T2; CNT++; } if(cnt==n-1) Break; } if(cnt<n-1)return-1;//Not Connected Else returnans;}intMain () {intN; intu,v,w; while(~SCANF ("%d",&N)) { if(n==0) Break; Tol=0; intm=n* (n1)/2; for(intI=0; i<m;++i) {scanf ("%d%d%d",&u,&v,&W); --u;--v; Addedge (U,V,W); } printf ("%d\n", Kruskal (N)); } return 0;}
View Code
HDU-1233 or unblocked project (minimum spanning tree)