UVA846 Steps

来源:互联网 发布:征服者升级软件 编辑:程序博客网 时间:2024/05/22 00:18

 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. Foreach 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 toget fromx toy.

Sample Input 

345 4845 4945 50

Sample Output 

334


题目意思就是给两个点,然后从一个点走到另一个点。最少多少步,第一步和最后一步都必须的1.而中间的步距离只能和前一步相等,或多一,或少一。

有一个规律就是相距 3的平方走 3 × 2 -1步,4的平方走 4 × 2 -1步。。i的平方走 i× 2 -1 步。比 i 的平方少 i-1的距离,也是走

i * 2 -1步。。更少就会少一步。


AC代码如下 :


#include<stdio.h>#include<math.h>#include<iostream>using namespace std; int main () {int t ;int x,y;int dis;scanf("%d",&t);while (t--) {scanf("%d%d",&x,&y);dis = y - x ;if (dis == 0) {printf("0\n");continue;}int i;for ( i = 1; ;i++) {if( i * i >= dis)break;}if(dis == i * i) {printf("%d\n", 2 * i - 1);continue;}else {dis = i * i - dis;if (dis < i)printf("%d\n",2 * i -1);elseprintf("%d\n",2 * i - 2);}}return 0;}


0 0
原创粉丝点击