这道题目的前置知识,曼哈顿距离,即为:$|x_1 - x_2| + |y_1 - y_2|$。

这是原来字母的标准位置,我们可以用一个结构体储存这几个字母的坐标,下标从 $0$ 开始

1
2
3
4
struct letter
{
int x,y;
}a[15] = {{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{2,4},{3,1},{3,2},{3,3},{3,4},{4,1},{4,2},{4,3}};//std

接下去是输入,用两层循环 for(int i = 1;i <= 4;i++)for(int j = 1;j <= 4;j++),$i$ 和 $j$ 正好表示输入的字母的坐标。我们现在要求的是所有字母从当前位置到自己的标准位置的曼哈顿距离之和,因此输入的.不需要被计算。那么这样只需要把 $i$ 与 $j$ 分别与该字母的标准进行比较求和就可以了。(注意:$\texttt{A}$ 的 $\text{ASCII}$ 的值等于 $65$,标准的下标从 $0$ 开始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cmath>
using namespace std;
struct letter
{
int x,y;
}a[15] = {{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{2,4},{3,1},{3,2},{3,3},{3,4},{4,1},{4,2},{4,3}};//std
int main()
{
int ans = 0;char ch;
for(int i = 1;i <= 4;i++)
{
for(int j = 1;j <= 4;j++)
{
cin>>ch;
if(ch != '.') ans += abs(a[ch - 65].x - i) + abs(a[ch - 65].y - j);//'A'的ASCII值为65
}
}
cout<<ans<<endl;
return 0;
}