Description

A triangle field is numbered with successive integers in the way shown on the picture below.
 

杭电OJ(1030题:Delta-wave



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

解决方案:

杭电OJ(1030题:Delta-wave杭电OJ(1030题:Delta-wave


#include<stdio.h>
#include<math.h>
int main()
{
    int a,b;
    int aX,aY,bX,bY,aLayer,bLayer,step;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        aLayer=ceil(sqrt((double)a));//求出数a所在层
        bLayer=ceil(sqrt((double)b));//求出数b所在层
        if(aLayer==bLayer)  printf("%d\n",abs(a-b));
        else
            {
                aX=(aLayer*aLayer-a)/2;//计算a的X坐标
                bX=(bLayer*bLayer-b)/2;//计算b的X坐标
                aY=(a-(aLayer*aLayer-2*aLayer+2))/2;//计算a的Y坐标
                bY=(b-(bLayer*bLayer-2*bLayer+2))/2;//计算b的Y坐标
                step=abs(aX-bX)+abs(aY-bY)+abs(aLayer-bLayer);
                printf("%d\n",step);//求出最终步骤
            }
    }
}
原文:https://blog.csdn.net/u014174811/article/details/41443177 

 

相关文章: