朋友圈(使用并查集)的实现
2016-07-09 23:25
260 查看
#pragma once
#include<iostream>
using namespace std;
class UnionFindSet
{
public:
UnionFindSet(int n)
{
_n = n + 1;
_set = new int[_n];
for (int i = 1; i < _n; ++i)
{
_set[i] = -1;
}
}
int GetFriendSet(int n, int m, int r[][2])
{
for (int i = 0; i < m; ++i)
{
UnionfriendSet(r[i][0],r[i][1] );
}
int count = 0;
for (int i = 1; i < _n; ++i)
{
if (_set[i] <0)
++count;
}
return count;
}
void UnionfriendSet(int n,int m)
{
int root1 = GetRoot(n);
int root2 = GetRoot(m);
if (root1 != root2)
{
_set[root1] += _set[root2];
_set[root2] = root1;
}
}
int GetRoot(int x)
{
while (_set[x] >= 0)
{
x = _set[x];
}
return x;
}
protected:
int *_set;
size_t _n;
};
#include<iostream>
using namespace std;
class UnionFindSet
{
public:
UnionFindSet(int n)
{
_n = n + 1;
_set = new int[_n];
for (int i = 1; i < _n; ++i)
{
_set[i] = -1;
}
}
int GetFriendSet(int n, int m, int r[][2])
{
for (int i = 0; i < m; ++i)
{
UnionfriendSet(r[i][0],r[i][1] );
}
int count = 0;
for (int i = 1; i < _n; ++i)
{
if (_set[i] <0)
++count;
}
return count;
}
void UnionfriendSet(int n,int m)
{
int root1 = GetRoot(n);
int root2 = GetRoot(m);
if (root1 != root2)
{
_set[root1] += _set[root2];
_set[root2] = root1;
}
}
int GetRoot(int x)
{
while (_set[x] >= 0)
{
x = _set[x];
}
return x;
}
protected:
int *_set;
size_t _n;
};
相关文章推荐
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- 我也有微信朋友圈了 Android实现
- 数据结构之Treap详解
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi