Algorithm Note _164: algorithm to improve the least squares of poor students into a tree (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

  1 problem description Problem DescriptionGiven the weighted graph, a spanning tree with the least variance is obtained. Input Formatenter multiple sets of test data. The first behavior is n,m, followed by the points and the number of sides. Next m line, three integers per line u,v,w, represents the edge of the connection u,v, and the weight value W. Ensure diagram connectivity. N=m=0 marks the end of the test file. output Formatfor each set of data, output the minimum variance, rounded to 0.01. The output format follows the sample. Sample Input4 5
1 2 1
2 3 2
3 4 2
4 1 1
2 4 3
4 6
1 2 1
2 3 2
3 4 3
4 1 1
2 4 3
1 3 3
0 0Sample OutputCase 1:0.22
Case 2:0.00data size and conventions

1<=u,v<=n<=50,n-1<=m<=1000,0<=w<=50. No more than 5 groups of data.

2 Solutions

This paper mainly examines the Kruskal algorithm, which focuses on the application of the algorithm, in search of the minimum square difference of the minimum spanning tree, you need to enumerate the mean value of the edge weights.

However, in accordance with this method, in the Blue Bridge practice system in the assessment has been 50 points, on the Internet to find some other users write C code, submission is also 50 points, may be Blue Bridge practice system background test data a bit of a problem, there may be the question enumerated accuracy is not enough.

The specific code is as follows:

Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;ImportJava.util.Scanner; Public classMain { Public Static intN, M;  Public Static DoubleMINV;//Enter the edge with the least weight in all edges     Public Static DoubleMAXV;//Enter the edge with the largest weight in all edges     Public Static int[] ID;  Public StaticArraylist<edge>map;  Public Staticarraylist<double> result =NewArraylist<double>(); classMycomparatorImplementsComparator<edge> {         Public intCompare (Edge arg0, Edge arg1) {if(Arg0.w >ARG1.W)return1; Else if(ARG0.W <ARG1.W)return-1; return0; }    }        Static classEdge { Public intA//the beginning of the side         Public intb//the end of the edge         Public DoubleV//weighted value of the edge         Public DoubleW//variance value of edge weights                 PublicEdgeintAintBDoublev) { This. A =A;  This. B =b;  This. v =v;  This. W = 0; }    }         Public voidinit () {MINV=Double.max_value; MAXV=Double.min_value; Map=NewArraylist<edge>(); }         Public intFindinta) {intRoot =A;  while(Id[root] >= 0) {root=Id[root]; }        intK =A, I;  while(k! =root) {i=Id[k]; ID[K]=Root; K=i; }        returnRoot; }         Public voidUnionintAintb) {intRoota =find (a); intROOTB =find (b); if(Roota = =ROOTB)return; intnum = Id[roota] +ID[ROOTB]; if(Id[roota] <ID[ROOTB]) {ID[ROOTB]=Roota; Id[roota]=num; } Else{Id[roota]=ROOTB; ID[ROOTB]=num; }    }         Public voidGetResult () {DoubleAVG =MINV; DoubleMinresult =Double.max_value;  for(; avg <= MAXV;AVG = avg + 0.3) {//here is the key to solving the problem, that is, enumerating the mean values of the Benquan of the smallest spanning tree             for(inti = 0;i < Map.size (); i++) {                Doublev = map.get (i). V-avg; Map.get (i). W= v *v; } collections.sort (Map,Newmycomparator ()); ID=New int[n + 1];  for(inti = 1;i <= n;i++) Id[i]=-1; Doublesum = 0; Double[] Value =New Double[N-1]; intCount = 0;  for(inti = 0;i < Map.size (); i++) {                intRoota =Find (Map.get (i). a); intROOTB =Find (Map.get (i). b); if(Roota! =ROOTB)                    {Union (Map.get (i). A, Map.get (i). b); Value[count++] =Map.get (i). V; Sum+=Map.get (i). V; if(Count = = n-1)                         Break; }} sum= SUM/(n-1); Doubletemp = 0;  for(inti = 0;i < value.length;i++) {Temp= temp + (Value[i]-sum) * (Value[i]-sum); } temp= Temp/(n-1); if(Minresult >temp) Minresult=temp;    } result.add (Minresult); }             Public Static voidMain (string[] args) {main test=NewMain (); Scanner in=NewScanner (system.in);  while(true) {n=In.nextint (); M=In.nextint (); if(n = = 0 | | m = = 0)                 Break;            Test.init ();  for(inti = 1;i <= m;i++) {                intA =In.nextint (); intb =In.nextint (); Doublev =in.nextdouble (); Map.add (NewEdge (A, B, v)); MINV=math.min (MINV, v); MAXV=Math.max (MAXV, v);        } test.getresult (); }         for(inti = 0;i < Result.size (); i++) {System.out.print ("Case" + (i+1) + ":"); System.out.printf ("%.2f", Result.get (i));        System.out.println (); }    }}

Algorithm Note _164: algorithm to improve the least squares of poor students into a tree (Java)

Related Article

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.