binset.h
huangyanbin · · 算法·理论
<binset.h> (并查集自制头文件)
/*
UpDate: 2026-01-08
Writer: huangyanbin
*/
#ifndef BINSET_H
#define BINSET_H 1
#include<unordered_map>
using namespace std;
template<typename Tp>
class binset
{
private:
unordered_map<Tp,Tp> f;
bool _pushed(Tp x)
{
return f.find(x)!=f.end();
}
void _push(Tp x)
{
if(!_pushed(x))
f[x]=x;
}
public:
Tp root(Tp x)
{
_push(x);
if(x==f[x])return x;
else return f[x]=root(f[x]);
}
void mergeto(Tp x,Tp y)
{
_push(x);
_push(y);
f[root(x)]=root(y);
}
bool inset(Tp x,Tp y)
{
return root(x)==root(y);
}
};
#endif
示例:洛谷P3367 使用"binset.h"
Luogu-P3367.cpp
#include <bits/stdc++.h>
#include "binset.h"
using namespace std;
binset<int> bin;
int n,m;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1; i<=m; i++)
{
int op,x,y;
cin>>op>>x>>y;
if(op==1) bin.mergeto(x,y);
else cout<<(bin.inset(x,y)?'Y':'N')<<'\n';
}
return 0;
}