Problem Description
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 Onput
3
方法一:(参考老师的方法进行具体实现)
找出数学规律,即可以把该金字塔中的数字M用坐标(x,y,z)进行定位,其实最短路径就是两个数M与N之间在x,y,z方向上(类似方法一法的分)的层差,例如:M=6,N=12,则坐标为(1,1,1),即三个方向的层差都是1其划分参考下图:
其x,y,z的运算方法如下:
x=(int)sqrt(m-1)+1;
y=(m-(x-1)*(x-1)+1)/2;
z=(x*x-m)/2+1;
源代码如下:
#include <iostream>
#include <cmath>
using namespace std;
void getPosition(int &x,int &y,int &z,int &mn){
x=(int)sqrt(mn-1)+1;//或者用ceil()函数进行向上取整
y=(mn-(x-1)*(x-1)+1)/2;
z=(x*x-mn)/2+1;
}
int main(){
int x1,y1,z1,x2,y2,z2,m,n,distance;
cin>>m>>n;
getPosition(x1,y1,z1,m);
getPosition(x2,y2,z2,n);
distance=abs(x1-x2)+abs(y1-y2)+abs(z1-z2);
cout<<distance;
return 0;
}
运行结果如图: