欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UVA10022 Delta-wave【找规律+数学题】

程序员文章站 2022-07-14 21:29:18
...

On the triangular field shown on the picture, small triangles are numbered from 1 to oo (infinity). Traveller wants to go from triangle M to triangle N. Traveller can move only through the sides of triangles, not vertices. The number of sides he crosses is called the path length.

  You are to determine the shortest path from M to N.

UVA10022 Delta-wave【找规律+数学题】

Input

The first line is the number of test cases, followed by a blank line.

  Each test case of the input contains integers M and N (1 ≤ M, N ≤ 1000000000), separated by some spaces.

  Each test case will be separated by a single line.

Output

For each test case, your programm should print the length of the shortest path from M to N. Print a blank line between the outputs for two consecutive test cases.

Sample Input

1

6 12

Sample Output

3


问题链接UVA10022 Delta-wave

问题简述:(略)

问题分析

  这是一个数学题,需要找出计算规律

  要想算出m到n的距离,需要从一个地方按行走、按左下方向走和按右下方向走,把这三个距离都加起来就得到了距离。

  这个题与参考链接的题应该说是同一个题,只是输入输出数据格式不同。

程序说明

  程序中的数组start[]和dest[]分别用于存储各行的起始值和终止值,然后搜索计算即可。

  上述这两个数组最大需要多大,可以通过条件编译语句先算一下。

题记:(略)

参考链接POJ2619 HDU1030 Delta-wave【找规律+数学题】


AC的C++语言程序如下:

/* UVA10022 Delta-wave */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

//#define DEBUG

using namespace std;

const int N = 1e9;
const int N1 = 32000;
int start[N1], dest[N1];

void init()
{
        int t = 1;
        for(int i=1, j=1; ;i+=2, j++)
        {
            start[j] = t;
            dest[j] = (t += i) - 1;
            if(t > N) {
#ifdef DEBUG
                printf("N2=%d\n", j);
#endif
                break;
            }
        }
}

int find(int x)
{
    for(int i=1; ;i++)
        if(x <= dest[i])
            return i;
}

int main()
{
    init();

    int t, m, n, ans;
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &m, &n);

        int mline = find(m);
        int nline = find(n);
        ans = abs(nline - mline) +
                abs((n - start[nline]) / 2 - (m - start[mline]) / 2) +
                abs((dest[nline] - n) / 2 - (dest[mline] - m) / 2);

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

        if(t)
            printf("\n");
    }

    return 0;
}