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
解题思路:
从三个不同的角度看这个三角形,算出起点和终点的三个不同的行差,相加就是需要移动的步数。
要用到ceil函数,在math.h头文件里,可以向上取最大整数。
#include<iostream>
#include<cmath>
using namespace std;
//ceil函数,向上取最大整数
int main()
{
int m,n;
while(cin>>m>>n)
{
int ml=(int)ceil(sqrt(m));
int nl=(int)ceil(sqrt(n));
int mz=(m-(ml-1)*(ml-1)+1)/2;
int nz=(n-(nl-1)*(nl-1)+1)/2;
int my=(ml*ml-m)/2+1;
int ny=(nl*nl-n)/2+1;
int ans=abs(ml-nl)+abs(mz-nz)+abs(my-ny);
cout<<ans<<endl;
}
}