UVA 846

来源:互联网 发布:win10安装软件打不开 编辑:程序博客网 时间:2024/06/04 19:11

  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$x$ \le$y < 231. For each test case, print a line giving the minimum number of steps to get from xto y.

Sample Input 

345 4845 4945 50

Sample Output 

334



参照寂静山岭大神的解题报告

源自http://blog.csdn.net/metaphysis/article/details/6533864

所走步数对应的序列如果左右对称,那么所走的步数应该是最少的。因为最先一步和最后一步长度均必须是

 1,又由于每一步的长度必须是非负整数,且要么比上一步步长恰好大 1,要么相等,要么小 1,则左右对
 称的序列能在最少步数得到最大距离。如果采取左右对称的走法,设两点距离为 distance,n = sqrt
 (distance),则由于最大步数为 n 步时能达到的距离是 1 + 2 + 3 + ... + (n - 1) + n +
 (n - 1) + ... + 3 + 2 + 1 = n^2。比较两点距离 distance 与 n^2,若相等,表明只需走
 2 * (n - 1) + 1 = 2 * n - 1 步,否则若剩余距离 distance - n^2 在 1 - (n + 1),

 只需插入一步即可,若 distance - n^2 大于 (n + 1),则需多插入两步即可。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int main(){    //freopen("in.txt" , "r" , stdin);    int Case ;    cin >> Case;    while(Case --)    {        int x, y , dis;        cin >> x >> y;        dis = y - x;        if(dis <= 3)cout << dis << endl;        else        {            int n = sqrt(dis);            if(n * n == dis)cout << 2 *n - 1 << endl;            else if(dis - n * n <= n)                cout << 2 * n << endl;            else                 cout << 2 * n + 1 << endl;        }    }    return 0;}/**/