L - Delta-wave
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
题意:给定一个如图所示的三角形,里面用连续的数字进行填充,给定两个数N,M,求从N到M的最短路线长度(只允许走边)
这道题卡了很久,参考了网上的文章https://blog.youkuaiyun.com/enjoying_science/article/details/38500755才写出来,将坐标转化为三维进行考虑,注意数据范围。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
long long m,n;
int step;
while(scanf("%I64d %I64d",&m,&n)!=EOF)
{
if(m>n)
{
long long temp=m;
m=n;
n=temp;
}
long long hm,hn,lm,ln,rm,rn;
hm=(long long )sqrt(m-1)+1;
hn=(long long )sqrt(n-1)+1;
lm=(m-(hm-1)*(hm-1)+1)/2;
ln=(n-(hn-1)*(hn-1)+1)/2;
rm=(hm*hm-m)/2+1;
rn=(hn*hn-n)/2+1;
step=abs(hm-hn)+abs(lm-ln)+abs(rm-rn);
printf("%d\n",step);
}
return 0;
}