标签:并查集
//并查集 #include <iostream> using namespace std; const int N = 100; const int M = 3; int parentSet[N]; int numRank[N]; void MakeSet() { //1、初始化,每个数字的parent都是它们自己 for (int i = 0; i < N; ++i){ parentSet[i] = i; numRank[i] = 0; } } int FindParent(int x) { if(x != parentSet[x]){ parentSet[x] = FindParent(parentSet[x]); } return parentSet[x]; } void UnionSet(int x, int y) { if ((x = FindParent(x)) == (y = FindParent(y)))return; if (numRank[x] < numRank[y]){ parentSet[x] = y; } else if (numRank[x]>numRank[y]){ parentSet[y] = x; } else{ parentSet[y] =x; ++numRank[x]; } } int main() { //人的编号从1开始 //哪些人属于一个圈 int relations[M][N] = { { 1, 2, 3 }, { 2, 3, 5 }, { 4 } }; MakeSet(); for (int i = 0; i < M; ++i){ int j = 1; while (relations[i][j] != 0){ UnionSet(relations[i][0], relations[i][j]); ++j; } } for (int i = 0; i < N; ++i){ cout << parentSet[i] << " "; } cout << endl; system("pause"); }
本文出自 “零蛋蛋” 博客,谢绝转载!
标签:并查集
原文地址:http://lingdandan.blog.51cto.com/10697032/1905309