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

来源:互联网 发布:知之者 编辑:程序博客网 时间:2024/05/21 17:06
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 0
原创粉丝点击