泥豪!我是2789617221guo!欢迎|

2789617221guo

园龄:1个月粉丝:2关注:2

2025-02-20 18:58阅读: 4评论: 0推荐: 0

洛谷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

本文作者:2789617221guo

本文链接:https://www.cnblogs.com/2789617221guo/p/18727438

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   2789617221guo  阅读(4)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起