码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1030 Delta-wave(找规律)

时间:2015-09-08 00:21:08      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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
 
题意:每一个点代表一个三角形,只有两个三角形有公共边时才能互通,可以采用坐标求法,每一个点当成一个坐标,该题要求出两个点之间的最短距离(横坐标绝对值和纵坐标绝对值之和)。
 
横坐标:由图可之,每一层有2*i-1个点(等差数列),那么只要我们找到Si==n,那么这个i就是我们要求的横坐标了(要注意可能Si<n,那么此时i+1才是我们要求的横坐标);
纵坐标:
技术分享   
                               a
技术分享
                                 b
图中1 2 3 4代表纵坐标,由于每一层的三角形都有两种形态,一种从左边开始(图a), 一种从右边开始(图b),所以我们要分别求出左边的列:mly = (m-(mx-1)*(mx-1)+1)/2,右边的列:mry = (mx*mx-m)/2+1;(当然这两个式子还有别的写法。。。)。
#include<stdio.h>
#include<math.h>
int main ()
{
    int m, n, mx, nx, mly, nly, mry, nry, ans, t;

    while(scanf("%d%d", &m, &n) != EOF)
    {
        if (m > n) 
        {
            t = m;
            m = n;
            n = t;
        }

        mx = (int)sqrt(m); ///计算行(横坐标)
        nx = (int)sqrt(n);

        if (mx * mx < m) mx++;
        if (nx * nx < n) nx++;

        mly = (m-(mx-1)*(mx-1)+1)/2;
        nly = (n-(nx-1)*(nx-1)+1)/2; ///计算从左边起的列(纵坐标)
        mry = (mx*mx-m)/2+1;
        nry = (nx*nx-n)/2+1; ///计算从右边起的列

        ans = fabs(mx-nx) + fabs(mly-nly) + fabs(mry-nry); ///两个点之间的最短距离就是横坐标绝对值和纵坐标绝对值之和

        printf("%d\n", ans);
    }

    return 0;
}

HDU 1030 Delta-wave(找规律)

标签:

原文地址:http://www.cnblogs.com/syhandll/p/4790179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!