HDOJ-1030

Delta-wave

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

Problem Description

A triangle field is numbered with successive integers in the way shown on the picture below.
img
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

分析:乍看像是最短路径问题,看一下规模:from 1 to 1000000000,知道肯定与图无关。那就应该是找规律题。发现最短路径长度s与横看层差数up与左看层差数left与右看层差数存在如下关系:\(s = up+left+right\)

接下来看看规律是否具有一般性:

从一个节点到另一个节点经过的边共有三类:—, , /。三类边数量的最少值总和即最短路径长度

"—"边的最少值即横看层差数,同理有左看层差数,右看层差数


#include <stdio.h>
#include <stdlib.h>
using namespace std;
int getup(int n)
{
    int sum = 0;
    int i = 0;
    do
    {
        i++;
        n -= 2 * i - 1;
    }
    while (n > 0);

    return i;
}
int getpos(int up, int n)
{
    for (int i = 1; i < up; i++)
    {
        n -= 2 * i - 1;
    }

    return n;
}
int getright(int pos)
{
    return (pos + 1) / 2;
}
int getleft(int up, int pos)
{
    int r = 2 * up - 1;

    int tmp = r - pos + 1;
    return getright(tmp);
}
int main()
{
    int m, n;
    while (scanf("%d %d", &m, &n) != EOF)
    {
        int m_up = getup(m);
        int m_p = getpos(m_up, m);

        int n_up = getup(n);
        int n_p = getpos(n_up, n);

        int up_off = m_up - n_up;
        if (up_off < 0) up_off = -up_off;

        int left_off = getleft(m_up, m_p) - getleft(n_up, n_p);
        if (left_off < 0)   left_off = -left_off;

        int right_off = getright(m_p) - getright(n_p);
        if (right_off < 0)  right_off = -right_off;

        printf("%d\n", up_off + left_off + right_off);
    }
}

posted @ 2018-03-26 14:53  Haruna_K  阅读(101)  评论(0编辑  收藏  举报