Test instructions: bare minimum spanning tree
Idea: minimum spanning tree template
1.prim
#include <iostream>#include<stdio.h>#include<string.h>using namespacestd;#defineINF 0x7fffffff#defineMAXN 128BOOLVIS[MAXN];intLOWC[MAXN];intPrimintCOST[][MAXN],intN) {//marking starting from 0 intans=0, I,j,minc,p; memset (Vis,false,sizeof(VIS)); vis[0]=true; for(i=1; i<n;++i) lowc[i]=cost[0][i]; for(i=1; i<n;++i) {Minc=INF; P=-1; for(j=0; j<n;++j)if(!vis[j]&&lowc[j]<minc) {Minc=Lowc[j]; P=J; } if(Minc==inf)return-1;//The original is not connectedans+=Minc; VIS[P]=true; for(j=0; j<n;++j)if(!vis[j]&&cost[p][j]<Lowc[j]) lowc[j]=Cost[p][j]; } returnans;}intMain () {intN,m,a,b,w,i; intCOST[MAXN][MAXN]; while(~SCANF ("%d", &n) &&N) {m=n* (n1)/2;//m side Stripe number for(i=0; i<m;++i) {scanf ("%d%d%d",&a,&b,&W); --a;--b; COST[A][B]=cost[b][a]=W; } printf ("%d\n", Prim (cost,n)); } return 0;}
View Code
2.kruskal
#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespacestd;#defineMAXN 110//maximum number of points#defineMAXM 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; 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, I,u,v,w,t1,t2; for(i=0; i<tol;++i) {u=edge[i].u; V=edge[i].v; W=EDGE[I].W; T1=find (U); T2=Find (v); if(t1!=T2) {ans+=W; F[T1]=T2; ++CNT; } if(cnt==n-1) Break; } if(cnt<n-1)return-1;//Not Connected returnans;}intMain () {intN,m,a,b,w,i; while(~SCANF ("%d", &n) &&N) {m=n* (n1)/2;//m side Stripe numberTol=0; for(i=0; i<m;++i) {scanf ("%d%d%d",&a,&b,&W); Addedge (A,B,W); } printf ("%d\n", Kruskal (n)); } return 0;}
View Code
HDU 1233 or unblocked project (minimum spanning tree)