and check Set

Source: Internet
Author: User

Today, the efficiency is good, learned a lot of things, of which there are and check set, of course, I only learned a small part, but also need to do more to consolidate and practice.

#include <iostream>using namespacestd;classDisjointset {Private:    int*father, *rank; Public: Disjointset (intsize) {Father=New int[size]; Rank=New int[size];  for(inti =0; i < size; ++i) {Father[i]=i; Rank[i]=0; }    }    ~Disjointset () {Delete[] Father; Delete[] rank; }    //Finding root Nodes    intFind_set (intnode) {        if(Father[node]! =node) {Father[node]= Find_set (Father[node]);//Path Compression Optimization        }        returnFather[node]; }    //Merging root nodes    BOOLMergeintNode1,intNode2) {        intAncestor1 =Find_set (Node1); intAncestor2 =Find_set (Node2); if(Ancestor1! =Ancestor2) {            if(Rank[ancestor1] >Rank[ancestor2])            {Swap (Ancestor1, ANCESTOR2); } Father[ancestor1]=Ancestor2; Rank[ancestor2]= Max (Rank[ancestor1] +1, Rank[ancestor2]);//Consolidation by rank optimization            return true; }        return false; }};intMain () {Disjointset DSU ( -); intm, x, y; CIN>>m;  for(inti =0; I < m; ++i) {cin>> x >>y; BOOLAns =dsu.merge (x, y); if(ans) {cout<<"Success"<<Endl; } Else{cout<<"failed"<<Endl; }    }    return 0;}

and check Set

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.