并查集写法板子
2026/6/3 17:51:54 网站建设 项目流程

我上的课的老师把洛谷P3367作为作业,我刚看到的时候是真的感觉一点都不会。

但是这是并查集的竞赛写法中第一简单的。

所以上课除了能听到噪音和打游戏看视频,真的有什么价值吗?

#include<iostream>
#include<vector>
#include<cstring>
#include<numeric>
using namespace std;
struct UF {
vector<int>f;
void init(int n) { f.resize(n + 1); iota(f.begin(), f.end(), 0); }
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
void unite(int x, int y) { f[find(x)] = find(y); }
bool same(int x, int y) { return find(x) == find(y); }
};
int main() {
int n,m;
cin >> n>>m;
UF uf;
uf.init(n);
while (m--) {
int a = 0; int b = 0; int tag = 0;
cin >> a >> b >> tag;
if (tag == 1)uf.unite(a, b);
else if (tag == 2) {
if (uf.same(a, b))cout << "Y" << endl;
else cout << "N" << endl;
}
else return -1;
}
return 0;
}
从写法的角度思考问题,这个程序看不见任何不好理解的地方。
但是并查集本身的概念,我觉得相当于手术信息的一种手段,我不太懂为什么上课要对这个概念扯这么久。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询