A weighted version of the fast merging algorithm for the 3--connectivity problem of Java algorithm

Source: Internet
Author: User

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

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.