UVa 808 (建坐标系、找规律) Bee Breeding

时间:2021-12-30 06:26:54

题意:

如图,按照图中的规律给这些格子编号。给出两个格子的编号,求从一个格子到另一个格子的最少步数。(一步只能穿过有有公共边的格子)

UVa 808 (建坐标系、找规律) Bee Breeding

分析:

根据高中数学知识,选任意两个不共线的向量,就能表示平面上所有点。

UVa 808 (建坐标系、找规律) Bee Breeding

像这样建立坐标系,根据图中的规律算出所有点的坐标。

推理也好,找找规律也好,不难发现

  • 第一、三象限的点(x, y)到原点的距离为 |x| + |y|
  • 第二、四象限的点(x, y)到原点的距离为 max{|x|, |y|}

递推点的坐标的时候也是比较注意细节的,否则很容易出错。

 #include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = ; struct Point
{
int x, y;
Point(int x=, int y=):x(x), y(y) {}
}p[maxn + ]; int dx[] = {-, -, , , , }; //六个方向
int dy[] = { , , , , -, -};
int pos; void cal(int dir, int l) //按照dir方向递推l个格子的坐标
{
pos++;
while(l--)
{
p[pos] = Point(p[pos-].x+dx[dir], p[pos-].y+dy[dir]);
pos++;
}
pos--;
} void Init()
{
p[] = Point(, -);
pos = ;
for(int l = ; l <= ; ++l)
{
for(int dir = ; dir < ; ++dir)
cal(dir, l);
cal(, l+);
cal(, l);
}
} int main()
{
Init(); int n, m;
while(scanf("%d%d", &n, &m) == && n)
{
int x = p[n].x - p[m].x;
int y = p[n].y - p[m].y;
int ans;
if((x<&&y>) || (x>&&y<)) ans = max(abs(x), abs(y));
else ans = abs(x+y); printf("The distance between cells %d and %d is %d.\n", n, m, ans);
} return ;
}

代码君