Title Link: http://www.lightoj.com/volume_showproblem.php?problem=1029
The main idea: a power station, to power the N house, any house between the wires directly or indirectly connected, now want to know the need to connect the average wire length of these houses. Average wire length = (maximum wire length + shortest wire length)/2;
Idea of problem solving: bare minimum spanning tree
The code is as follows:
#include <bits/stdc++.h>using namespacestd;Const intN =1003;structedge{ints, T, L; Edge () {} Edge (intSintTintl): s (s), T (t), L (l) {}};vector<edge>Vec;intPar[n], rank[n];intN;voidinit () { for(intI=0; i<=n; ++i) par[i]= i, rank[i] =0;}intFind (intx) { if(Par[x] = =x)returnx; Else returnPAR[X] =Find (par[x]);}voidUniteintXinty) {x= Find (x), y =Find (y); if(x = =y)return ; if(Rank[x] <Rank[y]) par[x]=y; Else{Par[y]=x; if(Rank[x] = =Rank[y]) RANK[X]++; }}BOOLSame (intXinty) { returnFind (x) = =Find (y);}BOOLcmpConstEdge &a,ConstEdge &b) { returnA.L <B.L;}BOOLCMP (ConstEdge &a,ConstEdge &b) { returnA.L >B.L;}intKruskal (intm) {init (); if(M = =1) sort (Vec.begin (), Vec.end (), CMP); Elsesort (Vec.begin (), Vec.end (), CMP); intres =0; for(intI=0; I<vec.size (); ++i) {edge e=Vec[i]; if(!Same (E.S, E.T)) {Unite (E.S, E.T); Res+=E.L; } } returnRes;}voidSolveintcases) {scanf ("%d", &N); Vec.clear (); while(1) { ints, T, L; scanf ("%d%d%d", &s, &t, &l); if((s | | | t | | l) = =false) Break; Vec.push_back (Edge (S, T, L)); } intAns =0; Ans+ = Kruskal (1); Ans+ = Kruskal (2); if(Ans &1) printf ("Case %d:%d/%d\n", cases, ans,2); Elseprintf ("Case %d:%d\n", cases, ans/2);}intMain () {intT; scanf ("%d", &t); for(intI=1; i<=t; ++i) solve (i); return 0;}
View Code
Light OJ 1029-civil and Evil Engineer (graph theory-minimum spanning tree)