POJ-2590-Steps题目详解,思路分析及代码,规律题,重要的是找到规律~~
Time Limit: 1000MS | Memory Limit: 65536K | |
http://poj.org/problem?id=2590
Description
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
Output
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;
}
最新文章
- Excel 同时打开2个或多个独立窗口
- subprocess使用
- delphi中通过CreateOleObject操控Word
- Stimulsoft Reports筛选数据来绑定显示2个报表
- UI2_ScrollView&;UIPageControl
- 大约sources.list和apt-get [转载]
- 使用Varnish+ESI实现静态页面的局部缓存(思路篇)
- jquery IE6 下animate 动画的opacity无效
- WPF中使用WebBrowser
- JS中的DOM— —节点以及操作
- 解决mysql表不能查询修改删除等操作并出现卡死
- JavaScript基础视频教程总结(051-060章)
- SAP 维护视图创建与修改
- conda常用命令总结
- Python邮件发送脚本(Linux,Windows)通用
- uniGUI试用笔记(十一)
- 利用crontab每天定时备份MySQL数据库
- 【CF671E】Organizing a Race 单调栈+线段树
- 2017 Tag Cloud
- css中用#id.class的形式定义样式,为什么这样用,不直接写成.class.代码如下:#skin_0.selected{}这种的