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

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.


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;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值