F.楼房的距离

版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/88104297

某小区的楼房全是一样的,并且按矩阵样式排列。其楼房的编号1,2,3…。
当排满一行时,从下一行相邻的楼往反方向排号。比如:当小区排号宽度为 6 时,开始情形如下:
1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 …
现在已知小区的宽度 w。问你两个楼号 n 和 m 对应的楼房之间的最短移动距离(只能上下左右移动)。

输入格式

输入第一行一个整数 w,表示小区的宽度。第二行输入两个整数 n,m,表示两个楼号。

输出格式

输出一个整数表示两个楼房的距离。

题解:我们可以模拟一遍,找到每个点的具体坐标,然后他们之间最短距离就 是 x 坐标的距离加上 y 坐标的距离。 如果我们是按照:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 …
这样计算,n的坐标为 (n / w, n % w)(下标从0开始),那么如果是奇数行, 只需要把y翻转一下即可。

#include <iostream>
#include <cmath>
using namespace std;
typedef long long int LL;
struct Point {
	LL x, y;
};
LL w;
Point getpoint(LL id)
{
	id--;
	Point res;
	res.x = id / w;
	res.y = id % w;
	if (res.x % 2)
	{
		res.y = w - res.y - 1;
	}
	return res;
}
int main()
{
	LL n, m;
	cin >> w >> n >> m;
	Point a1 = getpoint(n), a2 = getpoint(m);
	cout << abs(a1.x - a2.x) + abs(a1.y - a2.y) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/88104297