算法模板:输入输出,并查集

一、输入输出

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
#define int long long
#define endl '\n'

void solve()
{
	
}

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int _ = 1;
//	cin >> _;
	while(_--)
	{
		solve();
	}
	return 0;
}

二、并查集

Disjoint Set Union

中文:不相交集合合并 / 并查集

cpp 复制代码
struct DSU
{
	vector<int> fa, sz;
	DSU(int n) 
		:fa(n + 1)
		,sz(n + 1, 1) 
	{
		iota(fa.begin(), fa.end(), 0);	
	}
	int find(int x)
	{
		while(x != fa[x]) x = fa[x] = fa[fa[x]];
		return x;
	}
	int size(int x) 
	{
		return sz[find(x)];
	}
	bool same(int x, int y)
	{
		return find(x) == find(y);
	}
	bool merge(int x, int y)
	{
		x = find(x), y = find(y);
		if(x == y) return false;
		// 如果x的集合更大,就交换x和y,保证把小的挂到大的上
		if(sz[x] > sz[y]) swap(x, y);
		sz[y] += sz[x];
		fa[x] = y;
		return true;
	}
};
相关推荐
kyle~8 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾8 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
Flynt8 小时前
掘金热文说 Spring Boot 4.1 默认开虚拟线程,我实测后发现了更狠的坑
java·spring boot·性能优化
联犀8 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
Resean02239 小时前
Spring 源码分析(一)IOC 容器总览与 refresh() 全景
java·后端·spring
保利威视频SaaS小张9 小时前
企业直播接入笔记 12|企业内训直播怎么做签到和学时统计,防挂机这件事比想象中难
java·前端·数据库·笔记·视频云·polvy·polyv
牢姐与蒯9 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好10 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
lcj251110 小时前
[C++] C++11
开发语言·c++·笔记
顧棟11 小时前
【ES实战】 索引模板「可追溯、可校验」:一种模板治理的工程化思路
java·数据库·elasticsearch