hdu 1030 Delta-wave(数学题+找规律)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1030

Delta-wave

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7163    Accepted Submission(s): 2772


Problem Description
A triangle field is numbered with successive integers in the way shown on the picture below.

hdu 1030 Delta-wave(数学题+找规律)_第1张图片

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
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1035  1071  1027  1031  1041 
 
题目大意:数字按照所给图形进行排列,给出两点,求两点距离。
解题思路:图画大一点,然后找规律:固定这个数字的三维坐标,行很好找,直接将这个数开根号就可以知道是第几行,如果开根号正好是整数的话就直接是行号,否则需要加1,对于列有两个方向都需要进行求解。具体如下图:
第一种右斜着的列号: hdu 1030 Delta-wave(数学题+找规律)_第2张图片第二种是左斜着的列号: hdu 1030 Delta-wave(数学题+找规律)_第3张图片

根据这两种进行找规律。

详见代码。
#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int abs(int a)
{
    if (a>0)
        return a;
    else
        return -a;
}

int main()
{
    int a,b;
    while (~scanf("%d%d",&a,&b))
    {
        int h1=sqrt(a);
        if (h1*h1==a)
            h1=h1;
        else
            h1=h1+1;
        int h2=sqrt(b);
        if (h2*h2==b)
            h2=h2;
        else
            h2=h2+1;
        int r1=h1*h1;
        int rx1=(r1-a)/2+1;
        int r2=h2*h2;
        int rx2=(r2-b)/2+1;
        int l1=r1-(2*h1-1)+1;
        int lx1=(a-l1)/2+1;
        int l2=r2-(2*h2-1)+1;
        int lx2=(b-l2)/2+1;
        int ans=abs(h1-h2)+abs(lx1-lx2)+abs(rx1-rx2);
        cout<<ans<<endl;
    }
    return 0;
}





你可能感兴趣的:(C语言)