关键函数
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
find函数用来找出每个集合的根节点,然后进行路径压缩
让 x结点 直接指向根节点
例题:连通块中点的数量
https://www.acwing.com/problem/content/839/
并查集的应用 ,但是这题还要维护一个cnt 数组 用来记录每个集合点的数量
这里可以只维护根节点
#include <iostream>
using namespace std;
const int N = 100010;
int n,m;
int p[N],cnt[N];
int find(int x) //关键函数
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++) // 并查集初始化
{
p[i] = i; // 每个点的初始根节点为自己
cnt[i] = 1; // 每个点为一个集合且点的数量为1
}
while(m --)
{
string op;
int a, b;
cin >> op;
if(op == "C")
{
cin >> a >> b;
a = find(a),b = find(b);//找到两点的跟结点
if(a != b) //如果两点不在同一集合
{
p[a] = b;//将a 并到b上
cnt[b] += cnt[a];// 求合并后的点的数量 只维护根节点
}
}
else if(op == "Q1")
{
cin >> a >> b;
if(find(a) == find(b))puts("Yes");
else puts("No");
}
else
{
cin >> a;
cout << cnt[find(a)] << endl;//直接返回所在集合点数量
}
}
return 0;
}
例题:食物链
https://www.acwing.com/problem/content/242/
维护点到根节点的距离来判断动物是否为一类
#include <iostream>
using namespace std;
const int N = 50010;
int n,m;
int p[N],d[N];
int find(int x)
{
if(p[x] != x)
{
int t = find(p[x]);
d[x] += d[p[x]]; // 先更新距离
p[x] = t;//在更新根节点
}
return p[x];
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++)p[i] = i;
int res = 0;
while(m --)
{
int t , x, y;
cin >> t >> x >> y;
if(x > n || y > n) res ++;
else
{
int px = find(x),py = find(y);
if(t == 1)
{
if(px == py && (d[x] - d[y]) % 3)res ++;
else if(px != py)
{
p[px] = py;
d[px] = d[y] - d[x];
}
}
else
{
if(px == py && (d[x] - d[y] - 1) % 3)res ++;
else if(px != py)
{
p[px] = py;
d[px] = d[y] - d[x] + 1;
}
}
}
}
cout << res << endl;
return 0;
}