跳到正文

个人记录

未选择的路 题解

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

文章信息

收录
2025年12月12日
更新
2026年5月21日
篇幅
约 4 分钟

版本

  1. v1当前

首先考虑 nn 是奇数的情况。不难发现,你可以从起点开始,依次走完每一行,最后到达终点。下图是 n=3n=3 时的走法:

然后考虑 nn 是偶数的情况。可以证明,只能经过 n2−nn^2-n 个格子,且只有从左上到右下对角线的格子无法被经过。

证明:显然,对于某一个格子,只有一种经过它的方法(不考虑方向)。对于 n=6n=6 时,画出每个格子的对应对角线得到:

按照欧拉图的性质,存在一条通过图中每条边恰好一次的路径(即这张图能够被一笔画)当且仅当度数为奇数的点有最多两个,且它们为这条路径的起点或终点。

由于起点和终点度数均为 11,想要这张图能够被一笔画,其它节点的度数应当均为偶数。而最左上角与右下角的节点度数为奇数,两条标红色的边应被删掉而不被经过。

删除这两条边后,其另外一顶点度数减少一变为奇数,应当再删除以其为顶点的一条边,这就会导致另外一个节点度数减少一变为奇数,依次类推。

事实上,你需要删除一条从 (0,n)(0,n) 到 (n,0)(n,0) 的路径才能解决这个矛盾,此时 (0,n)(0,n) 和 (n,0)(n,0) 度数为 00,其余点要么度数没有减少,要么减少 22,符合能够一笔画的定义。

而显然,最短的一条从 (0,n)(0,n) 到 (n,0)(n,0) 的路径就为从左上到右下的对角线 。

这里给出一种合法的构造方式:采用递归的方式,从最外圈开始一圈一圈向内走,走到最中心后再向右上直接走到终点。下图是 n=6n=6 时的走法:

AC 代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
int n;
vector<pair<int, int>> res;
void update(int l, int r) {
	res.push_back({l + 1, l + 1});
	if (r - l == 2) return;
	int x = l + 1, y = l + 1;
	while (x + 2 <= r) {
		res.push_back({x + 1, y - 1});
		res.push_back({x + 2, y});
		x += 2;
	}
	while (y + 2 <= r) {
		res.push_back({x + 1, y + 1});
		res.push_back({x, y + 2});
		y += 2;
	}
	while (x - 2 >= l) {
		res.push_back({x - 1, y + 1});
		res.push_back({x - 2, y});
		x -= 2;
	}
	while (y - 2 >= l) {
		res.push_back({x - 1, y - 1});
		res.push_back({x, y - 2});
		y -= 2;
	}
	update(l + 1, r - 1);
}
int main() {
	scanf("%d", &n);
	if (n % 2 == 1) {
		printf("%d\n", n * n);
		int x = 0, y = 0;
		while (true) {
			while (x + 2 <= n) {
				res.push_back({x + 1, y + 1});
				res.push_back({x + 2, y});
				x += 2;
			}
			res.push_back({x + 1, y + 1});
			if (y == n - 1) break;
			res.push_back({x, y + 2});
			y += 2;
			while (x - 2 >= 0) {
				res.push_back({x - 1, y - 1});
				res.push_back({x - 2, y});
				x -= 2;
			}
		}
	}
	else {
		printf("%d\n", n * n - n);
		update(0, n);
		for (int i = n / 2 + 1; i <= n; i++)
			res.push_back({i, i});
	}
	for (pair<int, int> pr : res)
		printf("%d %d\n", pr.first, pr.second);
	return 0;
}
原文