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: 0![$ \le$](http://uva.onlinejudge.org/external/8/846img1.png)
![$ \le$](http://uva.onlinejudge.org/external/8/846img1.png)
Sample Input
3 45 48 45 49 45 50
Sample Output
3 3 4
题意:给定水平坐标轴上的两个位置,从一个位置走到另一个位置,第一步和最后一步长度都为1,中间的步子长度一定是比见面大1,或是相等,或是小1,求最少的步数。
注意,当两个数相等的时候,输出步数为0。
解析:很显然,这是一道找规律的题目,现在推一下规律:
两者之差 走法 步数
1 1 1
2 11 2
3 111 3
4 121 3
5 1211 4
6 1221 4
7 12211 5
8 12221 5
9 12321 5
10 123211 6
11 123221 6
12 123321 6
13 1233211 7
14 1233221 7
15 1233321 7
16 1234321 7
17 12343211 8
18 12343221 8
19 12343321 8
20 12344321 8
21 123443211 9
22 123443211 9
23 123443321 9
24 123444321 9
25 123454321 9
26 1234543211 10
由上表可知随着两者之差的增大,步数一次为1个1 , 1个2 ;2个3 , 2个4 ;3个5 , 3个6 ;4个7 , 4个8 ;5个9 , 5个10 ;6个11 , 6个12 ;7个13 , 7个14 ;8个15 , 8个16 ;9个17 , 9个18 。。。。。
1,2项合并,3, 4项合并,5, 6项合并。。。。,得到等差数列:
2,4,6,8,10,12,14.。。。。。,
该等差数列中每一个数代表合并的两项中包含的数的个数(即差的个数);
前n项和代表前n项所包含的差的总个数
这样一来,我们就可以根据两项的差找到所需最小步数最大可能在的位置。
即计算前n项和最先大于或等于差的位置,即下标,很巧的是,求出来的下标代表了原来合并的那两项所包含的的差的数目的一半。
根据求出来的下标计算该区间内的最小可能差,然后用题目中给的差减去最小可能差,求出区间内的步数。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int a,b,cha,sum,zx;
int i,j,k,n;
scanf("%d",&k);
while(k--)
{
scanf("%d%d",&a,&b);
cha = b - a;
if(cha == 0)
printf("0\n");
else
{
for(i = 1; i <= 10000; i++)
{
if(2 * i + i * (i - 1) >= cha)
break;
}
n = i;
sum = 2 * n + n * (n - 1);
zx = sum - 2 * n;
j = 2 + (n - 1) * 2;//合并区间内最大步数
if(cha - zx > n)
{
printf("%d\n",j);
}
else
printf("%d\n",j - 1);
}
}
return 0;
}