feat: 添加P6279题解实现并查集功能

实现基于并查集的解决方案来处理图的连通性问题,包括合并操作和查找操作。代码包含输入处理和结果输出逻辑,但存在传递性问题需要后续修复。
This commit is contained in:
Zengtudor 2025-09-30 21:10:54 +08:00
parent c0d1a2f156
commit eb451f8c09

46
src/9/30/P6279.cpp Normal file
View File

@ -0,0 +1,46 @@
#include <cstdint>
#include <iostream>
#include <istream>
#include <vector>
using ll = int64_t;
#define sl static inline
const ll maxn = 2e5+5;
ll n,m,ny=1;
ll f[maxn],ym[maxn],ys[maxn];
sl ll getf(ll a){
if(f[a]==a)return a;
return f[a]=getf(f[a]);
}
sl bool isame(ll a,ll b){
return getf(a)==getf(b);
}
sl void merge(ll a,ll b){
f[getf(a)]=getf(b);
}
int main(){
std::iostream::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin>>n>>m;
for(ll i=1;i<=n;i++)f[i]=i;
for(ll i=1;i<=m;i++){
ll a,b;
std::cin>>a>>b;
if(ym[a]){
merge(ym[a],b);
}else{
ym[a]=b;
}
}
for(ll i=1;i<=n;i++){
//TODO fix传递性问题
if(!ys[getf(i)]){
ys[getf(i)]=ny++;
}
std::cout<<ys[getf(i)]<<'\n';
}
}