C++并查集模板+应用
·
题一

图解

图源:Acwing
代码实现
#include<iostream>
using namespace std;
const int N=1e5+10;
int p[N];
int find(int x)
{
if(p[x] != x)
{
p[x] = find(p[x]);//查找根节点的同时实现路径压缩(p[x]直接指向x的根节点,不再指向上一节点)
}
return p[x];//最终返回的是x的根节点
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 1;i <= n;i++)//一开始时:每个p[x]=x,每个x都是自己的根节点
{
p[i] = i;
}
while(m--)
{
char op[2];
int a, b;
scanf("%s%d%d", op, &a, &b);//用%s读入可以避免读入空格,回车之类的干扰,
//cpp读入的优化
if(op[0] == 'M')
{
p[find(a)] = find(b);//将a的根节点所储存的元素变成b的根节点,实现两个集合的链接
}
else
{
if(find(a) == find(b))
{
cout<<"Yes"<<endl;
}
else
{
cout<<"No"<<endl;
}
}
}
return 0;
}
并查集应用
题二

图解

图源:Acwing
代码实现
#include<iostream>
using namespace std;
const int N=1e5+10;
int p[N],num[N];
int find(int x)
{
if(p[x] != x)
{
p[x] = find(p[x]);
}
return p[x];
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 1;i <= n;i++)
{
p[i] = i;
num[i] = 1;
}
while(m--)
{
string act;
cin >> act;
int a, b;
if(act == "C")
{
scanf("%d%d", &a, &b);
if(find(a) == find(b))
{
continue;
}
num[find(a)] +=num[find(b)];//必须先将b集合中的数加到a集合中,再将a,b相连;反过来会导致a集合元素的量直接乘2;
p[find(b)] = find(a);
}
else if(act == "Q1")
{
scanf("%d%d",&a, &b);
if(find(a) == find(b))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if(act == "Q2")
{
scanf("%d", &a);
printf("%d\n", num[find(a)]);
}
}
return 0;
}
题二

代码实现
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int p[N], dis[N], false_num;
int find(int x)
{
if(p[x] != x)
{
int temp = find(p[x]);
dis[x] += dis[p[x]];
p[x] = temp;
}
return p[x];
}
int main()
{
int n, k;
cin >> n >> k;
for(int i = 1;i <= n;i ++ )
{
p[i] = i;
}
while(k -- )
{
int D, x, y;
scanf("%d%d%d", &D, &x, &y);
if(x > n || y > n)
{
false_num ++ ;
continue;
}
int px = find(x), py = find(y);
if(D == 1)
{
if(px == py)//在同一链上and出现过
{
if((dis[x] - dis[y]) % 3 != 0)//判断是否是同一类
{
false_num ++ ;
}
}
else//不在同一链上or没出现过 认为是真话
{
p[px] = py;
dis[px] = dis[y] - dis[x];
}
}
else if(D == 2)
{
if(x == y)
{
false_num ++ ;
continue;
}
if(px == py)//在同一链上and出现过
{
if((dis[x] - dis[y] - 1) % 3 != 0)//认为x连接到y上,disx应该大于disy,所以用前者减去后者,下面也是一样
{
false_num ++ ;
}
}
else//不在同一链上or没出现过
{
p[px] = py;
dis[px] = dis[y] - dis[x] + 1;
}
}
}
cout << false_num << endl;
return 0;
}
}```
更多推荐


所有评论(0)