Title: http://poj.org/problem?id=1287
The problem is not much to say, the minimum generation tree template problem.
#include <cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespacestd;structnothing{int from, to, Val;} edge[10001];BOOLCMp (Nothing from, nothing to) { return from. val <To.val; } intN, M, father[Wuyi];voidinit () { for(inti =1; I <= N; i++) Father[i]=i;}intFind (inta) { if(A = =Father[a])returnA; Else returnFather[a] =Find (Father[a]);}BOOLMercy (intAintb) { intQ =Find (a); intP =Find (b); if(Q! =P) {Father[q]=P; return true; } return false;}intMain () { while(~SCANF ("%d", &N), N) {init (); scanf ("%d", &m); for(inti =0; I < m; i++) scanf ("%d%d%d", &edge[i]. from, &edge[i].to, &edge[i].val); Sort (edge, Edge+m, cMp); intsum =0; for(inti =0; I < m; i++) if(Mercy (edge[i). from, edge[i].to)) Sum+=Edge[i].val; printf ("%d\n", sum); } return 0;}
#include <cstdio>#include<cstring>#include<iostream>#defineM 51using namespacestd;Const intINF =0x3f3f3f3f;intN, M, Vis[m], dis[m], map[m][m];voidPrime () {intsum =0; memset (Vis,0,sizeof(VIS)); for(inti =1; I <= N; i++) Dis[i]= map[1][i]; vis[1] =1; for(inti =1; I < n; i++) { inttemp =1, Min =INF; for(intj =1; J <= N; J + +) { if(!vis[j] && Dis[j] <min) {Temp=J; Min=Dis[j]; } } if(min = =INF)return; Vis[temp]=1; Sum+=min; for(intj =1; J <= N; J + +) if(!vis[j] && dis[j] >Map[temp][j]) dis[j]=Map[temp][j]; } printf ("%d\n", sum);} intMain () { while(~SCANF ("%d", &N) {scanf ("%d", &m); for(inti =1; I <= N; i++) for(intj =1; J <= N; J + +) { if(i = =j) Map[i][j]=0; ElseMap[i][j]=INF; } for(inti =0; I < m; i++) { intA, B, C; scanf ("%d%d%d", &a, &b, &c); if(Map[a][b] >c) Map[a][b]= Map[b][a] =C; } Prime (); } return 0;}
Poj1287--networking (minimum spanning tree)