找规律题。
题目描述不能斜着走,也就是说最终的距离是两个楼房的行差的绝对值加上列差的绝对值。
如何求楼房的行列?设楼房x,宽度w
行好求:(x-1) /w即可。为什么要减一呢,因为楼房从1开始,假设宽度为4,第一行就是1,2,3,4。如果直接除w的话,求出的就是0,0,0,1可以看到同一行不同,所以必须要减一。
列:列因为有两种情况,正着来和反着来。只需要加一个行%2==0的判断即可。如果行%2==0就是正着来,列就是(x-1)%w【记下标从0开始】,如果行%2==1就反着来,列就是w-1-(x-1)%w【宽度减去从正着看的列数】。
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<math.h>
#include<set>
#include<string>
using namespace std;
int getIndex(int x, int w)
{
int level = (x-1) / w;
if (level % 2 == 0)
{
return (x-1) % w;//正着来
}
else
{
return w-1-(x-1)%w;//反着来
}
}
int main()
{
int w, m, n;
cin >> w >> m >> n;
cout << abs(getIndex(m, w) - getIndex(n, w)) + abs((m-1) / w - (n-1) / w);
return 0;
}