跳到正文

题解

上半场基础,下半场就也基础

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

题意:

目前没有翻译,还是给一下题意。

给定一张初始有 nn 个白点,没有边的无向图,有 qq 次如下操作:

  • 在两点之间添加一条边。
  • 将一个点的颜色反转。
  • 询问一个点是否是一个黑点或者可以到达黑点。

其中 n≤2×105,q≤6×105n\le 2\times10^5,q\le 6\times10^5。

解法:

操作中只有加边,并且需要维护可达性,联系数据范围,注意到并查集可以维护。由于题目要求我们关注是否可达黑点,所以我们需要维护连通块内的黑点数量。

此时就非常清晰了,对于操作一,将两点所在连通块合并;对于操作二,对点所在的连通块的黑点数量进行加减;对于操作三,查询点所在连通块的黑点数量是否等于 00 即可。

实现:

C++
#include<bits/stdc++.h>
using namespace std;
struct disjoint_set
{
	vector<int> fa,sz;
	disjoint_set(int n):fa(n+1),sz(n+1)
	{
		iota(fa.begin(),fa.end(),0);
	}
	int find(int u)
	{
		return u==fa[u]? u:fa[u]=find(fa[u]);
	}
	void merge(int u,int v)
	{
		u=find(u),v=find(v);
		if (u==v) return;
		fa[u]=v;
		sz[v]+=sz[u];
	}
};
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n,q,u,v,opt;
	cin>>n>>q;
	vector<int> col(n+1);
	disjoint_set dsu(n);
	while (q--)
	{
		cin>>opt>>u;
		if (opt==1)
		{
			cin>>v;
			dsu.merge(u,v);
		}
		else if (opt==2)
		{
			int anc=dsu.find(u);
			if (col[u]==0) dsu.sz[anc]++;
			else dsu.sz[anc]--;
			col[u]^=1;
		}
		else cout<<(dsu.sz[dsu.find(u)]? "Yes":"No")<<'\n';
	}
}

还没见过这么简单的 E 题。

原文