跳到正文

题解

题解:P17484 月兔通信网络

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

文章信息

发布
2026年9月25日
收录
2026年9月25日
更新
2026年11月10日
篇幅
约 2 分钟
题目
P17484

版本

  1. v1当前

解体思路

情况 1

考虑到最多连 n−1n-1 条边,选一个点连接其他所有边,图上最长距离不超过 22。

选择一个点,尝试与其他所有点建边。

情况 2

当 m−n×(n+1)2≤n−1m-\frac{n\times(n+1)}{2} \le n-1 时,补上不多于 n−1n-1 条边,就可以使得图成为完全图,图上最长距离距离为 11。

枚举点,判断缺失了什么边;无需担心超时,因为满足条件时 nn 不会很大。


特别的,重边用哈希判断即可。

参考代码

C++
#include <iostream>
#include <unordered_map>
using namespace std;
int t, n, m;
unordered_map<int, bool> Vis;
int main(){
	ios::sync_with_stdio(false);
	cin >> t;
	while (t--) {
		Vis.clear();
		cin >> n >> m;
		for (int i = 1; i <= m; i++) {
			int u, v;
			cin >> u >> v;
			if (u > v) swap(u, v);
			Vis[u * 10000 + v] = 1;
		}
		if (n * (n - 1) / 2 - Vis.size() <= n - 1) {
			cout << n * (n - 1) / 2 - Vis.size() << '\n';
			for (int i = 1; i < n; i++) for (int j = i + 1; j <= n; j++) if (!Vis[10000 * i + j]) cout << i << ' ' << j << '\n';
		} else {
			int Cnt = n - 1;
			for (int i = 2; i <= n; i++) if (Vis[10000 + i]) --Cnt;
			cout << Cnt << '\n';
			for (int i = 2; i <= n; i++) if (!Vis[10000 + i]) cout << "1 " << i << '\n';
		}
	}
	return 0;
}
原文