uva 846 - Steps

来源:互联网 发布:淘宝开店一个月没生意 编辑:程序博客网 时间:2024/05/01 14:17
  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 toy? 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$x$ \le$y < 231. For each test case, print a line giving the minimum number of steps to get fromx to y.

Sample Input 

345 4845 4945 50

Sample Output 

334

找规律

1:  1
2   1 1
3   1 1 1
4:  1 2 1
5   1 2 1 1
6   1 2 2 1
7   1 2 2 1 1
8   1 2 2 2 1
9:  1 2 3 2 1
10  1 2 3 2 1 1
11  1 2 3 2 2 1
12  1 2 3 3 2 1
13  1 2 3 3 2 1 1
14  1 2 3 3 2 2 1
15  1 2 3 3 3 2 1
16: 1 2 3 4 3 2 1

n*n:2*n-1


N*N-(N-1)*(N-1)-1
2*n-2

因为完全平方数的最小step是确定的所以,以完全平方数为界限。

n*n: 1......n......1                        minstep:2*n-1

.

.

n*(n+1)             1.....n,n.......1    minstep:2*n

.

.

(n+1)*(n+1) :1......n+1.........1   minstep:2*n+1

确定好分界线,忘记了0应该输出0,wrong了一次(Y-Y);

#include <stdio.h>
#include <math.h>
void main()
{int T,x,y,z,a;
 scanf("%d",&T);
 while (T--)
 {scanf("%d%d",&x,&y);
  if (y==x) printf("0");
  else
  {
  z=sqrt(y-x);
  if (z*z==y-x) printf("%d",2*z-1);
  else {a=z*z+z;if (y-x>a) printf("%d",2*z+1); else printf("%d",2*z);}
  }
  printf("\n");
 }
}
 

原创粉丝点击