Delta-wave

Delta-wave

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 35   Accepted Submission(s) : 9

Font: Times New Roman | Verdana | Georgia

Font Size:

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
 

#include<stdio.h>
#include<math.h>
void find(int n,int &l,int &r,int &level)
{
    int i;
    level=1;
    for(i=1;;i+=2)
    {
        if(n-i<=0)
        {
            l=(n+1)/2;
            r=(i-n)/2+1;
            break;
        }
        level++;
        n-=i;
    }
}

int main()
{
    int m,n;
    int ml,mr,nl,nr,mlevel,nlevel;
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        find(m,ml,mr,mlevel);
        find(n,nl,nr,nlevel);
        printf("%d\n",abs(ml-nl)+abs(mr-nr)+abs(mlevel-nlevel));
    }
    return 0;
}

/*  hdu   Delta-wave 每個數,求出相對頂層的層數 up,相對於三角形左邊界的層數 left, 相對於三角形右邊界的層數 right

任意兩個數的最短路徑等於  頂層差 +  左邊界差 + 右邊界差 */

#include<stdio.h>
#include<math.h>
int abs(int a)
{
    return (a>0)?a:-a;
}
int main()
{
    int m,n;
    int ml,mr,nl,nr;
    int up1,up2,left1,left2,right1,right2;
    while(scanf("%d%d",&m,&n)!=EOF)
    {

        up1 = (int)ceil(sqrt((double)m));	//數m對應從上開始的層數
        ml = (up1-1)*(up1-1)+1;				//up1層最左邊數的編號
        mr = up1*up1;		   				//up1層最右邊數的編號
        left1 = (m-ml)/2+1;					//從m 到 左邊界的層數 
        right1 = (mr-m)/2+1;				//從m 到 到右邊界的層數 


        up2 =  (int)ceil(sqrt((double)n));	//數n對應從上開始的層數
        nl = (up2-1)*(up2-1)+1;			    //up2層最左邊數的編號
        nr = up2*up2;		   				//up2層最右邊數的編號
        left2 = (n-nl)/2+1;					//從n 到 左邊界的層數 
        right2 = (nr-n)/2+1;				//從n 到 到右邊界的層數 
        printf("%d\n",abs(up2-up1)+abs(left2-left1)+abs(right2-right1));
    }
    return 0;
}*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章