洛谷P1259 黑白棋子的移动 题解

题目传送门

思路

可以使用递归来解此题。

我们发现,当我们把第 \(n\)\(n+1\) 个棋子移动到第 \(2\times n+1\)\(2\times n+2\) 的空位上,再把第 \(2\times n-1\)\(2\times n\) 个棋子移动到第 \(n\)\(n+1\) 的空位上后,就已经做好了一个o*,剩下的是同样相似于原问题的一个规模为 \(n-1\) 的子问题,此时我们就意识到,可以递归 \(dfs(n-1)\) 了。

\(n\le 4\) 时,需要特殊判定(因为没有规律嘛),输出

ooo--***o*
ooo*o**--*
o--*o**oo*
o*o*o*--o*
--o*o*o*o*

并在每行后面输出剩下的 \(2\times n-8\) 个棋子(不影响解题)。

解题完毕。

代码

#include<bits/stdc++.h>
#define endl '\n'

using namespace std;

const int INF = 0x3f3f3f3f;
const double EPS = 1e-8;
const int N = 205;

int n;
char chess[N];
void print(int x) {
	for(int i = x; i <= 2 * n + 2; i++) cout << chess[i];
	cout << endl;
}

void dfs(int d) {
	if(d <= 4) {
		printf("ooo--***o*");
		print(11);
		printf("ooo*o**--*");
		print(11);
		printf("o--*o**oo*");
		print(11);
		printf("o*o*o*--o*");
		print(11);
		printf("--o*o*o*o*");
		print(11);
		return;
	}
	chess[2 * d + 1] = 'o';
	chess[2 * d + 2] = '*';
	chess[d] = chess[d + 1] = '-';
	print(1);
	chess[d] = chess[d + 1] = '*';
	chess[2 * d - 1] = chess[2 * d] = '-';
	print(1);
	dfs(d - 1);
}

int main() {
	cin >> n;
	for(int i = 1; i <= n; i++) chess[i] = 'o';
	for(int i = n + 1; i <= 2 * n; i++) chess[i] = '*';
	chess[2 * n + 1] = chess[2 * n + 2] = '-';
	print(1);
	dfs(n);
	return 0;
}

AC记录

AC,18ms,576.00KB

posted @ 2025-02-20 18:58  2789617221guo  阅读(58)  评论(0)    收藏  举报