POJ2590 UVA846 ZOJ1871 Steps【模拟】

Steps

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8304   Accepted: 3783

Description

One steps through integer points of the straight line. The length of a step must be nonnegative and can be by one bigger than, equal to, or by one smaller than the length of the previous step. 
What is the minimum number of steps in order to get from x to y? The length of the first and the last step must be 1.

Input

Input consists of a line containing n, the number of test cases.

Output

For each test case, a line follows with two integers: 0 <= x <= y < 2^31. For each test case, print a line giving the minimum number of steps to get from x to y.

Sample Input

3
45 48
45 49
45 50

Sample Output

3
3
4

Source

Waterloo local 2000.01.29

问题链接POJ2590 UVA846 ZOJ1871 Steps

问题描述:(略)

问题分析

  如果走n步,按照题意公式能走的最长距离是1+2+3+4+...+(n+1)/2+...+4+3+2+1。能想到这一点,离解决问题就近了。

  在上述基础之上,可以推导数学公式,然后直接用数学公式进行计算。

  数学不强那就用模拟来解决,从两边到中间逐步模拟。

程序说明

  给出的程序是用模拟法实现的。

  ZOJ1871只是输入格式略有不同。

参考链接:(略)

题记

  没有好办法就模拟。虽然没有什么技术含量,但是可以解决问题,好在计算机算得快。

AC的C++语言程序(POJ2590,UVA846)如下:

/* POJ2590 UVA846 Steps */

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

using namespace std;

int main()
{
    int t;
    scanf("%d", &t);
    while(t--) {
        int x, y, dist, step = 1;
        scanf("%d%d", &x, &y);

        dist = y - x;
        int ans = 0;
        for(; ;) {
            if(dist <= 0)
                break;
            ans++;
            if((dist -= step) <= 0)
                break;
            ans++;
            if((dist -= step) <= 0)
                break;
            step++;
        }

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

    return 0;
}

AC的C++语言程序(ZOJ1871)如下:

/* ZOJ1871 Steps */

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

using namespace std;

int main()
{
    int x, y, dist, step;
    while(~scanf("%d%d", &x, &y)) {
        step = 1;
        dist = y - x;
        int ans = 0;
        for(; ;) {
            if(dist <= 0)
                break;
            ans++;
            if((dist -= step) <= 0)
                break;
            ans++;
            if((dist -= step) <= 0)
                break;
            step++;
        }

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

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/81784505