uva846 Steps

来源:互联网 发布:c语言在线编译运行 编辑:程序博客网 时间:2024/05/21 22:33

Steps
Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu
Submit Status Practice UVA 846
Appoint description:

Description
Download as PDF

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

/*Author:ZCC;Solve:// 所走步数对应的序列如果左右对称,那么所走的步数应该是最少的。因为最先一步和最后一步长度均必须是// 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<algorithm>#include<map>#include<cstdio>#include<cstdlib>#include<vector>#include<cmath>#include<cstring>#include<string>using namespace std;const int maxn=55;typedef long long LL;int a[maxn];int main(){    #ifndef ONLINE_JUDGE    //freopen("Text//in.txt","r",stdin);    #endif // ONLINE_JUDGE    int n,m;    int T;    scanf("%d",&T);    while(T--){        scanf("%d%d",&n,&m);        int dis=m-n;if(dis<=3){printf("%d\n",dis);continue;}        int y=(int) sqrt(dis);        if(y*y==dis){            printf("%d\n",y*2-1);        }        else if(dis-y*y<=y){            printf("%d\n",y*2);        }        else            printf("%d\n",y*2+1);    }    return 0;}
0 0
原创粉丝点击