ACM-简单题之Delta-wave——hdu1030

Delta-wave
题目: http://acm.hdu.edu.cn/showproblem.php?pid=1030
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


这道题是当时我听大一ACMer讲的一道题目,

回来,自己也做了一下,因为听了他们的思路,所以就很快A了,

但是,其中有点小差错啊。

该题目简便的想法就是:(以7为例)

将每一个数字的位置用三个层数来描述,

首先,最直观的就是从上往下数的——第3层,

从左向右数的——第2层 (第一层是   1 3 2 6 5 11 10)

从右向左数的——第2层 (第一层是   1 3 4 8 9 15 16)

我刚开始以为的是将这三个数加起来,算输入的两个数的层差之和。

显然是不对的,

正确的应该是算  两个数  每一个不同方向层差(绝对值)的和。

这次,函数用了引用,不需要设置全局变量了。


#include <iostream>
#include <cmath>
using namespace std;

int jdz(int a)
{
    return a<0?-a:a;
}

void find_ceng(int x,int &l,int &r,int &s)
{
    double ss;
    ss=sqrt(double(x));
    if(int(ss)!=ss)   ss+=1;
    s=int(ss);
    // 求出该数所在层,第一个数据和最后一个数据
    int start,finish;
    start=(s-1)*(s-1)+1;
    finish=s*s;
    l=(x-start)/2+1;
    r=(finish-x)/2+1;
}

int main()
{
    int m,n;
    // s记录竖直方向,l记录左端开始的层数,r记录右端开始的层数
    int m_s,m_l,m_r,n_s,n_l,n_r;
    while(cin>>m>>n)
    {
        find_ceng(m,m_l,m_r,m_s);
        find_ceng(n,n_l,n_r,n_s);
        cout<<jdz(m_l-n_l)+jdz(m_r-n_r)+jdz(m_s-n_s)<<endl;
    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值