并查集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
- 并查集C++源码
- 并查集C++源码
- C语言 并查集
- [c] poj2524 并查集
- 并查集—C
- java 实践源码--并查集
- 不相交集(并查集)(C++)
- 并查集(C语言)
- 并查集实现(C语言)
- 并查集C - More is better
- CodeForces 218C 并查集
- 【CodeForces】445C Civilization 并查集
- C语言 并查集基础
- C语言 并查集 压缩路径
- codeforces 650C (并查集)
- 并查集的实现c
- codeforce C. Learning Languages(并查集)
- codeforces 722C (并查集)
- Android之在linux环境不通过TAG快速过滤日志
- C实例---二维数组(指针实现)
- opencv之改变图像尺寸
- Python爬虫中的Get和Post方法
- Fragment + RadioGroup 实现类似于Tab的效果
- 并查集C++源码
- PAT 1011 A+B和C
- PHP检测文件方法,类方法是否存在
- directx初第七卷
- 算法提高 盾神与条状项链
- directx初第八卷
- 后面抽空看一下
- ExternalStorage存放音乐,通过Notification播放音乐,并震动的Demo
- apue:进程关系