In the merger operation, we do not randomly connect the second tree to the first tree, but note the number of nodes per tree, when merging, always to the number of nodes with a smaller number of node count. This change requires a bit more code to modify, but also requires an array to hold the number of nodes, but the efficiency of the program is improved a lot, we call this algorithm "weighted fast merging algorithm."
Public class quickuw{ public static void main (String[] args) { int n=integer.parseint (args [0]); int id[]=new int[N],sz[]=new int[N]; for (int i=0;i<n;i++) { id[i]=i; sz[i]=1; } for (In.init ();! In.empty ();) { int i,j,p=in.getint (), Q=in.getint (); for (I=p;i!=id[i];i=id[i]); &NBSP;&NBSp; for (J=q;j!=id[i];j=id[j]); if (I==J) continue; if (Sz[i]<sz[j]) { id[i]=j; sz[j]+=sz[i]; } else { id[j]=i; sz[j]+=sz[j]; } }}
The weighted fast merging algorithm constructs a forest in which the path in the tree is much shorter than the path of the tree in the non-weighted merging algorithm. In the worst case, the collection size to be merged is always equal (the collection size is a power of 2). Although the structure of this tree looks complex, they have a simple nature, that is, in a tree with 2 n power nodes, the maximum number of connections to reach the root is N.
Properties: Weighted fast merge algorithm to determine whether two objects in N objects are connected, up to 2lgN lines.
This article is from the "Flying Fish Technology" blog, please be sure to keep this source http://flyingfish.blog.51cto.com/9580339/1622575
A weighted version of the fast merging algorithm for the 3--connectivity problem of Java algorithm