跳到正文

题解

题解:CF2060E Graph Composition

dingxiongyue约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年2月9日
收录
2026年10月20日
更新
2026年10月20日
篇幅
约 4 分钟
获赞
4
题目
CF2060E

版本

  1. v1当前

题解:CF2060E Graph Composition

Description:

给出两个无向图 FF 与 GG,可对 FF 进行加边或减边,求使 FF 与 GG 连通性一致的最小操作次数。

Analysis:

可以使用并查集来维护图的连通性,但减边操作不容易实现。

对于图 FF,可以建立两个并查集 f1f1 与 f2f2。f1f1 维护未进行操作的图 FF,f2f2 维护减边后的图 FF。

分别先后遍历 FF 与 GG 的所有边。

  • 若 FF 中一条边两端点的连通性与 GG 不同,则跳过该条边,否则,将该边加入并查集 f2f2,并累计贡献加 11。
  • 若 GG 中一条边两端点的连通性与 FF 不同,则将该边加入并查集 f2f2,并累积贡献加 11,否则,跳过该边。

时间复杂度 O(T⋅Nα(N))O(T \cdot N \alpha(N))。

Code:

AC记录

C++
#include <iostream>

#define int long long
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
int T;
int n, m1, m2;
int x, y;
int ans;
int f1[N], f2[N], f[N];
PII a[N], b[N];
inline int read() {
	int x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * f;
}

inline void write(int x) {
	if (x < 0) putchar('-'), x = -x;
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}

void init() {
	for (int i = 1; i <= n; i++) 
		f1[i] = f2[i] = f[i] = i;
}

int find(int x, int t) {
	if (t == 0) return x == f[x] ? f[x] : f[x] = find(f[x], 0);
	else if (t == 1) return x == f1[x] ? f1[x] : f1[x] = find(f1[x], 1);
	else return x == f2[x] ? f2[x] : f2[x] = find(f2[x], 2);
}

signed main() {
	T = read();
	while (T--) {
		ans = 0;
		n = read(), m1 = read(), m2 = read();
		init();
		for (int i = 1; i <= m1; i++) {
			x = read(), y = read();
			f1[find(y, 1)] = find(x, 1);
			a[i] = {x, y};
		}
		for (int i = 1; i <= m2; i++) {
			x = read(), y = read();
			f[find(y, 0)] = find(x, 0);
			b[i] = {x, y};
		}
		for (int i = 1; i <= m1; i++) {
			if (find(a[i].x, 0) != find(a[i].y, 0)) ans++;
			else f2[find(a[i].y, 2)] = find(a[i].x, 2);
		}
		for (int i = 1; i <= m2; i++) 
			if (find(b[i].x, 2) != find(b[i].y, 2)) {
				ans++;
				f2[find(b[i].x, 2)] = find(b[i].y, 2);
			}
		write(ans);
		printf("\n");
	}
	return 0;
}
原文