并查集
2025-04-13 10:27:39
发布于:江苏
2阅读
0回复
0点赞
/*
* @filename:~/Documents/workspace/vscode_space
* @author: Ly_boy
* @date: 2025-04-10 14:47:51 星期四
* @compiler: 2025 by Ly_boy, All Rights Reserved.
*/
#include <bits/stdc++.h>
#define endl "\n"
#define debug freopen("in.txt", "r", stdin), freopen("out.txt", "w", stdout)
using namespace std;
int t, n, m, p, u, v, fa[5005]; // n:点数 m:关系 p:询问 u,v:边的两个端点 fa:并查集数组
int find(int x) // 查找x的根节点
{
if (x == fa[x])
return x;
return fa[x] = find(fa[x]);
}
void union1(int x, int y) // 合并x,y两个集合
{
int fx = find(x), fy = find(y);
if (fx != fy)
fa[fx] = fy;
}
void solve()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
fa[i] = i; // 初始化并查集
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &u, &v);
union1(u, v); // 合并u,v两个点
}
int cnt = 0;
for (int i = 1; i <= n; i++)
if (fa[i] == i)
cnt++; // 统计集合个数
printf("%d\n", cnt);
}
int main()
{
scanf("%d", &t);
while (t--)
solve();
return 0;
}
这里空空如也
有帮助,赞一个