并查集
#include<bits/stdc++.h>
//#define LOCAL
#define sum(a) ( accumulate ((a).begin(), (a).end(), 0int))
#define mine(a) (*min_element((a).begin(), (a).end()))
#define maxe(a) (*max_element((a).begin(), (a).end()))
#define mini(a) ( min_element((a).begin(), (a).end()) - (a).begin())
#define maxi(a) ( max_element((a).begin(), (a).end()) - (a).begin())
#define yes cout<<"YES"<<'\n'
#define no cout<<"NO"<<'\n'
#define print(x) cout<<(x)<<'\n'
#define print_v(x) for (int iii = 0; iii < (x).size(); ++iii) {cout << (x)[iii] << " \n"[iii==(x).size()-1];}
using namespace std;
#define mp make_pair
#define int long long
const int inf = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 2e5 + 5;
int fa[MAXN];
int cnt = 0;
int n, p, m;
void init() {
for (int i = 0; i <= n; ++i) {
fa[i] = i;
}
}
int find(int x) {
if (x == fa[x])
return x;
else {
fa[x] = find(fa[x]);
return fa[x];
}
}
void merge(int i, int j) {
int x = find(i), y = find(j);
if (x == y)return;
fa[y] = x;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
#ifdef LOCAL
freopen("output.txt", "w", stdout);
freopen("input.txt", "r", stdin);
#endif
cin >> n >> m >> p;
init();
int x, y;
while (m--) {
cin >> x >> y;
merge(x, y);
}
while (p--) {
cin >> x >> y;
cout << (find(x) == find(y) ? "Yes" : "No") << '\n';
}
}权值维护
路径压缩
启发式合并


Reference
最后更新于