A triangle field is numbered with successive integers in the way shown on the picture below.
The traveller needs to go from the cell with number M to the cell with number N. The traveller is able to enter the cell through cell edges only, he can not travel from cell to cell through vertices. The number of edges the traveller passes makes the length of the traveller’s route.
Write the program to determine the length of the shortest route connecting cells with numbers N and M.
Input
Input contains two integer numbers M and N in the range from 1 to 1000000000 separated with space(s).
Output
Output should contain the length of the shortest route.
Sample Input
6 12
Sample Output
3
题解
题意 :
- 大三角形区域如图,内部是有规律的排列的小室。给定数字m,n,求m到n的最小步数。只能在大三角形内穿过短边,不能通过定点,穿过短边数目为步数。
思路:
- 实例模拟:假设N点为3,M点为7,可以让N点斜向左下一格,使N,M在斜右下方向上处于同一列,再让N向下一格,使处于同一行,N再斜向右下一格,到达M点。
- 发现:要使N,M重合,必须使之处于同一行,在斜右下方向处于同一列,在斜左下方向处于同一列。所以定义三个坐标(行,斜左下列,斜右下列),各个坐标之差的绝对值之和就是最小移动步数。斜左下列从右上往左下数,斜右下列从左上往右下数。
Code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int m, n;
while (cin >> m >> n)
{
int a1 = sqrt(m - 1) + 1;//行坐标
int a2 = sqrt(n - 1) + 1;
int b1 = (m - (a1 - 1) * (a1 - 1) + 1) / 2;//斜左坐标
int b2 = (n - (a2 - 1) * (a2 - 1) + 1) / 2;
int c1 = (a1 * a1 - m + 2) / 2;//右斜坐标
int c2 = (a2 * a2 - n + 2) / 2;
cout << abs(a1 - a2) + abs(b1 - b2) + abs(c1 - c2) << endl;
}
}