2013秋13级预备队集训练习4 --B - Steps


  Steps 

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 and Output 

Input consists of a line containing n, the number of test cases. For each test case, a line follows with two integers: 0xy < 231. 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

该题中,一次只能加一或减一,并且开始和最后都是1,提问要最小的步骤,那么意思就是在向前走的时候,要让中间的数尽量大,所以可以先将它看为左右对称,然后令i从1开始向上加,每次都加它的两倍 对应左右两边 , 那么最后会有三种情况,1、剩余的数小于等于i ,那么它可以认为将i之前的某一个数重复加一遍 2、剩余的数小于2*i 大于i,那么我们能认为是一个i和一个比 i小的数相加 3、剩余的数大于2*i 那么剩余的数减去2*同时i++; 进入下一次循环  最后得到最少次数


#include <stdio.h>
int main()
{
    int i , n , t , x , y , j , count ;
    scanf("%d", &n);
    for(i = 1 ; i <= n ; i++)
    {
        scanf("%d %d", &x, &y);
        count = 0 ;
        t = y - x ;
        for(j = 1 ; ; j++)
        {
            if(t <= 0) break;
            if(t > 2*j)
            {
                t -= 2 * j ;
                count += 2 ;
            }
            else if(t > j)
            {
                count += 2 ;
                break;
            }
            else if(t > 0)
                {
                    count++;
                    break;
                }
        }
        printf("%d\n", count);

    }
}


你可能感兴趣的:(2013秋13级预备队集训练习4 --B - Steps)