ACM(HDOJ 1030 Delta-wave)金字塔问题

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 Onput
3

这里写图片描述

方法一:(参考老师的方法进行具体实现)
找出数学规律,即可以把该金字塔中的数字M用坐标(x,y,z)进行定位,其实最短路径就是两个数M与N之间在x,y,z方向上(类似方法一法的分)的层差,例如:M=6,N=12,则坐标为(1,1,1),即三个方向的层差都是1其划分参考下图:
这里写图片描述
这里写图片描述
这里写图片描述
其x,y,z的运算方法如下:

x=(int)sqrt(m-1)+1;
y=(m-(x-1)*(x-1)+1)/2;
z=(x*x-m)/2+1;

源代码如下:

#include <iostream>
#include <cmath>

using namespace std;

void getPosition(int &x,int &y,int &z,int &mn){
    x=(int)sqrt(mn-1)+1;//或者用ceil()函数进行向上取整
    y=(mn-(x-1)*(x-1)+1)/2;
    z=(x*x-mn)/2+1;
}

int main(){
    int x1,y1,z1,x2,y2,z2,m,n,distance;
    cin>>m>>n;
    getPosition(x1,y1,z1,m);
    getPosition(x2,y2,z2,n);
    distance=abs(x1-x2)+abs(y1-y2)+abs(z1-z2);
    cout<<distance;   

    return 0;
}

运行结果如图:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值