UVA 846 - Steps(数学)

来源:互联网 发布:化学查询软件下载 编辑:程序博客网 时间:2024/05/18 00:53

 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 x to y.

Sample Input 

345 4845 4945 50

Sample Output 

334



Miguel Revilla 2002-06-15

==============================

第一步为1,最后一步也为1,连续两步的大小只能相等或相差1,从坐标x走到坐标y,输出最少的步数


因为两边大小是固定的所以大小往中间逐渐加1,如果最后剩下的大小不够一步的话,一定可以调整前面的步子大小使之可以成为一步。这样就是最少的步数


#include <iostream>using namespace std;int main(){    int t,x,y;    cin>>t;    while(t--)    {        cin>>x>>y;        int d=y-x;        int step=1,ans=0,flag=0;        while(d>0)        {            d-=step;            ans++;            if(flag) step++;            flag=!flag;        }        cout<<ans<<endl;    }    return 0;}

原创粉丝点击