Code implementation:
packagecom.qiusongde;Importedu.princeton.cs.algs4.StdIn;Importedu.princeton.cs.algs4.StdOut; public classufweightedquickunion {Private int[] id;//Parent Link (site indexed) Private int[] treesize;//size of component for roots (site indexed) Private intCount// number of components Private Static intTotalCost = 0;//For the test of array access publicUfweightedquickunion (intN) {count=N; ID=New int[N]; for(inti = 0; I < N; i++) id[i]=i; TreeSize=New int[N]; for(inti = 0; I < N; i++) treesize[i]= 1; } public intCount () {returncount; } public BooleanConnectedintPintQ) {returnFind (p) = =Find (q); } public intFindintP) { while(p! =Id[p]) {p=id[p]; TotalCost+ = 2; } totalcost++; returnp; } public voidUnionintPintQ) {intProot =Find (p); intQroot =Find (q); if(proot = =Qroot)return; //make smaller root point to larger one if(treesize[proot] <treesize[qroot]) {id[proot]=qroot; treesize[qroot]+=treesize[proot]; TotalCost+ = 5; } Else{id[qroot]=proot; treesize[proot]+=treesize[qroot]; TotalCost+ = 5; } Count--; } @Override publicstring toString () {string s= ""; for(inti = 0; I < id.length; i++) {s+ = id[i] + ""; } s+ = "\ n"; for(inti = 0; I < treesize.length; i++) {s+ = treesize[i] + ""; } s+ = "\ n" + count + "components"; returns; } public Static voidmain (string[] Args) {//Initialize N components intN =Stdin.readint (); Ufweightedquickunion uf=Newufweightedquickunion (N); Stdout.println (uf); Stdout.println (); while(!Stdin.isempty ()) { intp =Stdin.readint (); intQ =Stdin.readint (); if(uf.connected (p, Q)) {//Ignore if connectedStdout.println (p + "" + q + "is Connected")); Stdout.println ("totalcost:" +totalcost); Stdout.println (); Continue; } uf.union (p, q);//Connect p and QStdout.println (p + "" +q); Stdout.println (uf); Stdout.println ("totalcost:" +totalcost); Stdout.println (); } } }
Reference Input:
104 33 86 59 42 18 95 07 26 11 06 7
Results:
0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 10 components4 30 1 2 4 4 5 6 7 8 9 1 1 1 1 2 1 1 1 1 1 9componentstotalcost:93 80 1 2 4 4 5 6 7 4 9 1 1 1 1 3 1 1 1 1 1 8componentstotalcost:226 50 1 2 4 4 6 6 7 4 9 1 1 1 1 3 1 2 1 1 1 7componentstotalcost:319 40 1 2 4 4 6 6 7 4 4 1 1 1 1 4 1 2 1 1 1 6componentstotalcost:402 10 2 2 4 4 6 6 7 4 4 1 1 2 1 4 1 2 1 1 1 5componentstotalcost:498 9is connectedtotalcost:555 06 2 2 4 4 6 6 7 4 4 1 1 2 1 4 1 3 1 1 1 4componentstotalcost:687 26 2 2 4 4 6 6 2 4 4 1 1 3 1 4 1 3 1 1 1 3componentstotalcost:776 16 2 6 4 4 6 6 2 4 4 1 1 3 1 4 1 6 1 1 1 2componentstotalcost:901 0is connectedtotalcost:986 7is connectedtotalcost:104
Worst-case input:
80 12 34 56 70 24 60 4
Results:
0 1 2 3 4 5 6 7 1 1 1 1 1 1 1 1 8 0 0 2 3 4 5 6 7 2 1 1 1 1 1 1 1 792 30 0 2 2 4 5 6 7 2 1 2 1 1 1 1 1 6184 0 2 2 4 4 6 7 2 1 2 1 2 1 1 1 5276 0 2 2 4 4 6 6 2 1 2 1 2 12 1 4 360 20 0 0 2 4 4 6 6 4 1 2 1 2 1 2 1 3454 0 0 2 4 4 4 6 4 1 2 1 4 1 2 1 2540 40 0 0 2 0 4 4 6 8 1 2 1 4 1 2 1 163
Algorithm (algorithms) version 4th practice 1.5.4