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,求从m到n的最小步数,只能从细胞边缘进入另一个,不能从定点进入。很明显找规律,找啊找,哪有那么好找,最后求助与博客,才知道方法和规律:以三角形建立三维坐标,坐标相减的绝对值加起来就是最小步数,像这样子,x=(int)sqrt(n-1)+1,y=(n-(x-1)*(x-1)+1)/2,z=(x*x-n)/2+1; 这个规律不是人人都找得出来的我也找不出来,这就是智商差距吧。有了理论代码就简单了
#include<iostream>
#include<cmath>
using namespace std;
int row(int a);
int col(int a,int b);
int zuo(int a,int b);
int main()
{
 int n,m,step;
 int x1,y1,z1,x2,y2,z2;
 while(cin>>n>>m)
 {
  x1=row(n);
  y1=col(n,x1);
  z1=zuo(n,x1);
  x2=row(m);
  y2=col(m,x2);
  z2=zuo(m,x2);
  step=abs(x1-x2)+abs(y1-y2)+abs(z1-z2);
  cout<<step<<endl;
 }
}
int row(int a)
{
 return (int)sqrt(a-1)+1;
}
int col(int a,int b)
{
 return (a-(b-1)*(b-1)+1)/2;
}
int zuo(int a,int b)
{
 return (b*b-a)/2+1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值