Light OJ 1029-civil and Evil Engineer (graph theory-minimum spanning tree)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.