HDU---1030-Delta-wave (简单数学)

本文介绍了一种解决三角网格中两点间最短路径问题的算法。该算法应用于从编号为M的单元格到编号为N的单元格寻找最短路径,通过计算单元格所在行数及位置来确定路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Delta-wave

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 2
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

Source

Ural Collegiate Programming Contest 1998


 

 

 

<pre name="code" class="cpp">#include <iostream>
#include <cmath>
#include <cstdio>
#include <iomanip>
using namespace std;
int main()
{
    int a,b;  // 10亿
    while(cin>>a>>b)
    {
        if(a>b)swap(a,b);
        int sum;
        int x=pow((double)(a-1),0.5)+1;  // 顶部当前行
        int y=pow((double)(b-1),0.5)+1;  // 底部当前行
        if(x==y)
        {
            cout<<b-a<<endl;
            continue;
        }
        int ylen = y-x;            //行差
        int xx=a-(x-1)*(x-1);      //当前坐标
        int yy=b-(y-1)*(y-1);      //当前坐标
        int sum1,sum2;
        if((xx%2==1 && yy<=xx+2*ylen && yy>=xx) || (xx%2==0 && yy<=xx+2*ylen+1 && yy>=xx-1))  //内部覆盖判断
        {
            sum=2*ylen;
            if(yy%2==0)--sum;      // 底部倒三角
            if(xx%2==1)--sum;      // 顶部正三角
        }
        else                       // 外部
        {
            if(xx%2==0)            //顶部倒三角
            {
                if(yy<xx-1)        //覆盖区域左边
                    sum=xx-1-yy+2*ylen;
                else
                    sum=yy-xx-1;   //右边
            }
            else                   //顶部正三角
            {
                if(yy<xx)          //覆盖区域左边
                    sum=xx-yy+2*ylen-1;
                else
                    sum=yy-xx-1;   //右边
            }
        }
        cout<<sum+1<<endl;
    }
    return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值