数据结构【并查集(模板+例题)】
前言
并查集 :
实现集合的快速合并与查找
用树存储一个集合
如果两个点有共同的跟,他们就在一个集合里
合并两个点所在集合只需要吧一个点的根接到另一个点的跟下边
一、并查集是什么?
一个很有趣的小姐姐解说并查集的链接: link.
二、模板
代码如下(示例):
#include<iostream>
using namespace std;
int fa[10010];//存储结构
int find(int root)
{
int son = root; //记录初始节点,以便路径压缩
while(root != fa[root])
{
root = fa[root];
}
while(son != root) //路径压缩
{
int temp = fa[son];//记录son的父节点
fa[son] = root;//将son的父节点变成结合的根节点
son = temp;//迭代son成为父节点
}
}
void unit(int x,int y)
{
int root1 = find(x);
int root2 = find(y);
if(root1 != root2)
{
fa[root1] = root2;
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) //初始化
{
fa[i]=i;
}
while(m--)
{
int start,end;
cin>>start>>end;
int root1 = find(start); //找两个点的根节点
int root2 = find(end);
unit(start,end); //合并
}
return 0;
}
例题
链接:https://ac.nowcoder.com/acm/problem/16884
来源:牛客网
题目描述
动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形。A吃B,B吃C,C吃A。 现有N个动物,以1-N编号。每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种。 有人用两种说法对这N个动物所构成的食物链关系进行描述: 第一种说法是“1 X Y”,表示X和Y是同类。 第二种说法是“2 X Y”,表示X吃Y。 此人对N个动物,用上述两种说法,一句接一句地说出K句话,这K句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。 1) 当前的话与前面的某些真的话冲突,就是假话; 2) 当前的话中X或Y比N大,就是假话; 3) 当前的话表示X吃X,就是假话。 你的任务是根据给定的N(1≤N≤50,000)和K句话(0≤K≤100,000),输出假话的总数。
链接:https://ac.nowcoder.com/acm/problem/16884
来源:牛客网
输入
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
输出
3
思想:
从一句话开始,将正确的关系合并 。
对于同类的判断 :
不知道x,y是那种动物,就假设x是A(由于每次加入集合操作,都把x,y对应的三个物种都加入,所以只需要判断一种情况)
则如果y是B或C类,即正确的关系集合中有 x—y+n 说明x,y 是吃与被吃的关系 就说明当前的话不正确
find(x) == find(y+n) || find(x) == find(y+2*n);
对吃的判断:
如果 在正确关系集合中发现 x,y是同类 或者x被y吃 则不正确
find(x) == find(y) || find(x) == find(y+2*n);
AC代码:
#include<iostream>
using namespace std;
int fa[200000]; //开三倍的数组 0 - n-1 存A;n - n*2-1 存B;
int n,m;
int find(int root) //查找
{
int son;
son = root;
while(root != fa[root])
{
root = fa[root];
}
while(son != root) //压缩
{
int temp = fa[son];
fa[son] = root;
son = temp;
}
return root;
}
void unit(int x,int y) //合并
{
int root1 = find(x);
int root2 = find(y);
if(root1 != root2)
{
fa[root1] = root2;
}
}
int main()
{
cin>>n>>m;
int ans = 0;
for(int i=0;i<3*n;i++)
{
fa[i]=i;
}
for(int i=0;i<m;i++)
{
int k,x,y;
cin>>k>>x>>y;
if(x>n || y>n)
{
ans++;
continue;
}
if(k==1)
{
if(find(x) == find(y+n) || find(x) == find(y+2*n))
{
ans++;
}
else//这句话和之前的正确集合不冲突,把这句话加入正确集合。
{
unit(x,y);//由于不知道x,y种类,就把x,y 对应的三个物种都加入
unit(x+n,y+n);
unit(x+2*n,y+2*n);
}
}
else //判断x吃y关系
{
if(find(x) == find(y) || find(x) == find(y+2*n))//如果 在正确关系集合中发现 x,y是同类 或者x被y吃 则不正确
{
ans++;
}
else
{
unit(x,y+n);//与之前正确集合不冲突,则加入集合。
unit(x+n,y+2*n);
unit(x+2*n,y);
}
}
}
cout<<ans;
return 0;
}
还有几个例题,慢慢补上。