p2820局域网并查集算法
时间: 2023-11-12 22:58:59 浏览: 56
p2820是一道关于并查集的题目,主要思路是将每个点看作一个集合,然后通过合并集合的方式来判断两个点是否在同一个连通块中。具体实现可以使用路径压缩和按秩合并的优化方式,可以参考以下代码:
```c++
#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN = 100010;
int fa[MAXN], rank[MAXN];
void init(int n) {
for (int i = 1; i <= n; i++) {
fa[i] = i;
rank[i] = 0;
}
}
int find(int x) {
if (fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
void merge(int x, int y) {
int fx = find(x), fy = find(y);
if (fx == fy) return;
if (rank[fx] < rank[fy]) swap(fx, fy);
fa[fy] = fx;
if (rank[fx] == rank[fy]) rank[fx]++;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
init(n);
for (int i = 1; i <= m; i++) {
int op, x, y;
scanf("%d%d%d", &op, &x, &y);
if (op == 1) merge(x, y);
else {
if (find(x) == find(y)) printf("Y\n");
else printf("N\n");
}
}
return 0;
}
```
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)