[HNOI2006]马步距离
做题日期:2020.11.21
\(【题目描述】\)
在一个棋盘上有一匹马,行走路径为日字形,给定起点坐标\((sx,sy)\)与终点坐标\((ex,ey)(sx,sy,ex,ey \leq 10^7)\),问从起点走到终点最短距离是多少?
\(【样例输入】\)
1 2 7 9
\(【样例输出】\)
5
\(【考点】\)
贪心
\(【做法】\)
简化问题,求出起点与终点的横纵坐标差,即定义\(x=|sx-ex|,y=|sy-ey|\),将起点看成原点,终点看成\((x,y)\)。接着使用贪心策略:每走一步肯定都是向着终点方向前进,而马只能走日字,因此每一次如果横坐标大于纵坐标,则横坐标-2,纵坐标-1,反之要么横坐标-1,纵坐标-2。直到\(x \leq 4,y \leq 4\)的时候,可以直接利用题目中的表格进行打表。
\(【代码】\)
#include<cstdio>
#include<iomanip>
using namespace std;
int a[5][5]={{0,3,2,3,2},//在原表达基础上进行一些拓展
{3,2,1,2,3},
{2,1,4,3,2},
{3,2,3,2,3},
{2,3,2,3,4}};
int n,m;
int Abs(int a){return a<0?-a:a;}
int main()
{
int sx,sy,ex,ey;
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
int x=Abs(sx-ex);
int y=Abs(sy-ey);//将起点看成(0,0),终点看成(x,y)
int ans=0;
while(x>4||y>4){
x=Abs(x),y=Abs(y);
if(x<y) x--,y-=2;//哪个大就往哪边走
else x-=2,y--;
ans++;
}
printf("%d\n",ans+a[x][y]);//最后加上表格中的数据
return 0;
}

浙公网安备 33010602011771号