跳到正文

算法·理论

binset.h

huangyanbin约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年1月8日
收录
2026年1月29日
更新
2026年10月28日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

<binset.h> (并查集自制头文件)

C++
/*
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

C++
#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;
}
原文