链接:https://ac.nowcoder.com/acm/contest/7865/A
来源:牛客网
Elma is learning chess figures.
She learned that a rook can move either horizontally or vertically. To enhance her understanding of rook movement Elma’s grandmother gave Elma an 8 × 8 chess board and asked her to find a way to move the rook from a1 to h8 making exactly n moves, so that all visited cells are different.
A visited cell is the initial cell a1 and each cell on which the rook lands after a move.
输入描述:
The input contains a single integer n (2 ≤ n ≤ 63) — the desired number of moves.
输出描述:
Output a space-separated list of n+1 visited cells in the order they are visited by the rook. All cells must be different. The list should start with a1 and end with h8. A solution always exists.
示例1
输入
复制
4
输出
复制
a1 f1 c1 c8 h8
题意:
你可以横着走也可以竖着走(车),要求不重复遍历n个格子,最后到终点。
思路:
2~50的部分可以走(1,1)到(7,7)的部分
51~56的部分,先从(1,1)依次走到(7,7),再从(8,7)依次走n-48-1格子,再走到终点。
57~63的部分,依次遍历完(1,1)到(5,8)的格子,再从(5,8)遍历到(7,8)。这就遍历了56步。再在最后一行遍历剩下的格子。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 5005;
const int mod = 1e9 + 7;
vector<pair<int,int> >ans;
int get1(int n) {
//弄到前x步, 3~51
int cnt = 0;
int x = 1,y = 1;
for(int i = 1;i <= 7;i++) {
if(i & 1) {
for(int j = 1;j <= 7;j++) {
cnt++;
if(cnt > n) break;
ans.push_back({
i,j});
x = i;y = j;
}
} else {
for(int j = 7;j >= 1;j--) {
cnt++;
if(cnt > n) break;
ans.push_back({
i,j});
x = i;y = j;
}
}
if(cnt > n) break;
}
return y;
}
void get2(int n) {
//52~57
get1(49);
n -= 49;
n--;
for(int i = 7;i >= 7 - n + 1;i--) {
ans.push_back({
i,8});
}
ans.push_back({
8,8});
}
void get3(int n) {
//58~64
for(int i = 1;i <= 5;i++) {
if(i & 1) {
for(int j = 1;j <= 8;j++) {
ans.push_back({
i,j});
}
} else {
for(int j = 8;j >= 1;j--) {
ans.push_back({
i,j});
}
}
}
int x = 5,y = 8;
for(int i = 1;i <= 8;i++) {
if(i & 1) {
ans.push_back({
++x,y});
ans.push_back({
++x,y});
} else {
ans.push_back({
x--,y});
ans.push_back({
x--,y});
}
y--;
}
n -= 56;
n--;
for(int i = 1;i <= n;i++) {
ans.push_back({
8,i});
}
ans.push_back({
8,8});
}
void Print() {
for(int i = 0;i < ans.size();i++) {
printf("%c%d ",ans[i].second - 1 + 'a',ans[i].first);
}
}
int main() {
int n;scanf("%d",&n);
n++;
if(n <= 51) {
int y = get1(n - 2);
ans.push_back({
8,y});
ans.push_back({
8,8});
} else if(n <= 57) {
get2(n);
} else {
get3(n);
}
Print();
return 0;
}