Steps
Time Limit: 1000MS   Memory Limit: 65536K
     

http://poj.org/problem?id=2590

Description

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

Input consists of a line containing n, the number of test cases.

Output

For each test case, a line follows with two integers: 0 <= x <= y < 2^31. 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

Source

题目意思很好懂:求x点到y点的最小步数,起始和结束的都只能走一步,中间的可以等于前一步,可以比前一步大一或小一;

我们可以推算出,假设走n步,所能达到的最长距离为:1+2+3+4+...+(n+1)/2+...+4+3+2+1;明白了吧,1  2  3  4  5 ...(n+1)/2... 5  4  3  2  1   ;是不是很熟悉;;

步数(n):        最大距离                                                        f(n)

1                 1                                                                         f(1)=1;

2                 1 + 1                                                                   f(2)=2=f(1)+(2+1)/2;

3                 1 + 2 + 1                                                             f(3)=4=f(2)+(3+1)/2;

...                   ...                                                                        ...

n                  1 + 2 + 3 +...+ (n+1)/2 +...+ 3 + 2 +1               f(n)=f(n-1)+(n+1)/2;

这样的话方法就多了,可以把距离与步数的关系打表,然后算出距离差,二分查找即可,但开始我有个疑问,如果这个差值介于f(n)与f(n-1)之间怎么办,我们知道n-1步所能达到的最大距离是f(n-1),如果f(n-1)还比差值小,那么无论如何n-1步都是无法达到的,即只能在n步达到;

这里介绍一种很好的方法,代码简洁易懂,思路都差不多;

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int find(int x)
{
int i,a=1;
for(i=2;;i++)
{
a+=(i+1)/2;//a为i步能达到的最大距离,这样连打表都不用了;
if(a>=x)
break;
}
return i;
}
int main()
{
int t,a,b;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
if(b-a<=3)
printf("%d\n",b-a);//革除了a b 相等的情况;
else
printf("%d\n",find(b-a));
}
return 0;
}

最新文章

  1. Excel 同时打开2个或多个独立窗口
  2. subprocess使用
  3. delphi中通过CreateOleObject操控Word
  4. Stimulsoft Reports筛选数据来绑定显示2个报表
  5. UI2_ScrollView&amp;UIPageControl
  6. 大约sources.list和apt-get [转载]
  7. 使用Varnish+ESI实现静态页面的局部缓存(思路篇)
  8. jquery IE6 下animate 动画的opacity无效
  9. WPF中使用WebBrowser
  10. JS中的DOM— —节点以及操作
  11. 解决mysql表不能查询修改删除等操作并出现卡死
  12. JavaScript基础视频教程总结(051-060章)
  13. SAP 维护视图创建与修改
  14. conda常用命令总结
  15. Python邮件发送脚本(Linux,Windows)通用
  16. uniGUI试用笔记(十一)
  17. 利用crontab每天定时备份MySQL数据库
  18. 【CF671E】Organizing a Race 单调栈+线段树
  19. 2017 Tag Cloud
  20. css中用#id.class的形式定义样式,为什么这样用,不直接写成.class.代码如下:#skin_0.selected{}这种的

热门文章

  1. 在sz
  2. 记录两个python itchat的用法博客网址
  3. 【转】grep 用法详解
  4. Excel数据直接到DataTable---&gt;DB
  5. AJPFX总结内部类
  6. AJPFX总结匿名类及其使用
  7. Spring-bean(零)
  8. B/S网络架构
  9. 第3章 接口与API设计 52条笔记
  10. jstat查看JVM的GC情况