并查集C++源码

来源:互联网 发布:c语言控制鼠标点击 编辑:程序博客网 时间:2024/05/01 12:25

一、UniteFind.h源码

#pragma once#include "stdafx.h"class UniteFind{private :    int* nodeRoot;    int* treeHeight;    int nodeNum;    int findRoot(int node)    {        while (nodeRoot[node] != node)        {            node = nodeRoot[node];        }         return node;    }public:    UniteFind(int n)    {        nodeRoot = new int[n];        treeHeight = new int[n];        for(int i=0; i<n; i++)        {            nodeRoot[i] = i; //每个节点的树根是自己            treeHeight[i] = 0;        }        nodeNum = n;    }    ~UniteFind()    {        delete[] nodeRoot;        delete[] treeHeight;        nodeRoot = nullptr;        treeHeight = nullptr;    }    void unite(int a, int b)    {        if(a==b || a <0 || a>=nodeNum || b <0 || b>=nodeNum)        {            return;        }        int aRoot = findRoot(a);        int bRoot = findRoot(b);        //根据树的高度,将高度低的树根的父节点设置成高度高的树根        if(treeHeight[aRoot] < treeHeight[bRoot])        {            nodeRoot[aRoot] = bRoot;        }        else        {            nodeRoot[bRoot] = aRoot;            if(treeHeight[aRoot] == treeHeight[bRoot])            {                aRoot++;            }        }    }    bool isOneUnite(int a, int b)    {        if(a==b || a <0 || a>=nodeNum || b <0 || b>=nodeNum)        {            return false;        }        return findRoot(a) == findRoot(b);    }    int getUniteNum()    {        int num = 0;        for(int i=0;i<nodeNum; i++)        {            if(nodeRoot[i] == i)            {                num++;            }        }        return num;    }};

二、UniteFindTest.h源码

#pragma  once#include "stdafx.h"#include "UniteFind.h"class UniteFindTest{public:    void doTest()    {        UniteFind unitFind(10);        unitFind.unite(0,3);        unitFind.unite(2,4);        unitFind.unite(2,3);        unitFind.unite(5,7);        unitFind.unite(6,8);        unitFind.unite(9,6);        cout << (unitFind.isOneUnite(2,0)?"true":"false") <<endl;        cout << (unitFind.isOneUnite(3,5)?"true":"false") <<endl;        cout << unitFind.getUniteNum() << endl;    }};
0 0
原创粉丝点击