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 Output:
3
解题思路:
就是一个找规律的题, 用三个坐标(行 左列 右列 例如12的坐标为423)把每个数的位置找出来,最短路程就是各个坐标之差的绝对值的和。
程序代码:
#include<iostream> #include<cstdio> #include<cmath> using namespace std; int main() { int ans,a[4],b[4],n,m; while(cin>>n>>m) { a[1]=sqrt(n-1)+1;//行坐标 a[2]=(n-(a[1]-1)*(a[1]-1)+1)/2;//左列坐标 a[3]=(abs(n-a[1]*a[1])+2)/2;//右列坐标 b[1]=sqrt(m-1)+1; b[2]=(m-(b[1]-1)*(b[1]-1)+1)/2; b[3]=(abs(m-b[1]*b[1])+2)/2; ans=abs(a[1]-b[1])+abs(a[2]-b[2])+abs(a[3]-b[3]); cout<<ans<<endl; } return 0; }