Delta-wave

来源:互联网 发布:淘宝一元秒杀 编辑:程序博客网 时间:2024/05/01 13:31
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
从三个角度看这个图,level,left,right,如下图,题目的答案就是3个图上2个点之间的层数的高度差之和。

例如 6 12 ,level=1,left=1,right=1,答案就是3。

例如 3 12 ,level=2,left=1,right=2,答案就是6。

水平方向是level = sqrt(num - 1) + 1,左侧的坐标可以表示为:left = ( level*level - num)/ 2 +1, 
右侧的坐标可以表示为:right = (num- (level-1)*(level-1) - 1)/ 2 + 1
那么剩下的就是将两个点的三个坐标的值对应求差然后去绝对值再求和就可以了。
#include<stdio.h>#include<iostream>#include<string.h>#include<math.h>using namespace std;int abs(int a){    if(a<0)        return -a;        else            return a;}int main(){    int n,m;    while(scanf("%d%d",&n,&m)!=-1)    {        int a1=sqrt(n-1)+1;        int b1=sqrt(m-1)+1;        int a2=(a1*a1-n)/2+1;        int b2=(b1*b1-m)/2+1;        int a3=(n-(a1-1)*(a1-1)-1)/2+1;        int b3=(m-(b1-1)*(b1-1)-1)/2+1;        printf("%d\n",abs(a1-b1)+abs(a2-b2)+abs(a3-b3));    }}

0 0
原创粉丝点击