C++구현 및 검색 집합
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class UnionFind{
private:
vector<int> parent;
int count;
// , p q ,
vector<int> rank;
public:
UnionFind(int count){
parent.resize(count);
rank.resize(count);
this->count = count;
for(int i = 0; i < count; ++i){
parent[i] = i;
rank[i] = 1;
}
}
~UnionFind(){
parent.clear();
rank.clear();
}
//
int find(int p){
assert(p >= 0 && p < count);
if(p != parent[p])
parent[p] = find(parent[p]);
return parent[p];
}
bool isConnected(int p, int q){
return find(p) == find(q);
}
void unionElement(int p, int q){
int pRoot = find(p), qRoot = find(q);
if(pRoot == qRoot)
return;
if(rank[pRoot] < rank[qRoot])
parent[pRoot] = qRoot;
else if(rank[qRoot] < rank[pRoot])
parent[qRoot] = pRoot;
else{
// rank
parent[pRoot] = qRoot;
rank[qRoot] += 1;
}
}
};
작은 편집 은 코드 를 한 단락 더 보충 합 니 다.이전에 소장 하고 있 던 코드 입 니 다.
#include <iostream>
using namespace std;
class UF {
//cnt is the number of disjoint sets.
//id is an array that records distinct identity of each set,when two sets are merged ,their id will be same.
//sz is an array that records the child number of each set including the set self.
int *id, cnt, *sz;
public:
// Create an empty union find data structure with N isolated sets.
UF(int N) {
cnt = N;
id = new int[N];
sz = new int[N];
for (int i = 0; i<N; i++) {
id[i] = i;
sz[i] = 1;
}
}
~UF() {
delete[] id;
delete[] sz;
}
// Return the id of component corresponding to object p.
int find(int p) {
if (p != id[p]){
id[p] = find(id[p]);
}
return id[p];
}
// Replace sets containing x and y with their union.
void merge(int x, int y) {
int i = find(x);
int j = find(y);
if (i == j) return;
// make smaller root point to larger one
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i] += sz[j];
}
cnt--;
}
// Are objects x and y in the same set?
bool connected(int x, int y) {
return find(x) == find(y);
}
// Return the number of disjoint sets.
int count() {
return cnt;
}
};
void main(){
UF test(5);
test.merge(2, 3);
test.merge(3, 4);
cout << test.find(4);
cout << test.count();
}
그리고 이 작가 님 의 공유 에 감 사 드 립 니 다.이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Visual Studio에서 파일 폴더 구분 (포함 경로 설정)Visual Studio에서 c, cpp, h, hpp 파일을 폴더로 나누고 싶었습니까? 어쩌면 대부분의 사람들이 있다고 생각합니다. 처음에 파일이 만들어지는 장소는 프로젝트 파일 등과 같은 장소에 있기 때문에 파일...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.