Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7913 | Accepted: 3632 |
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
解题思路:
由于第一步和最后一步都只能为一步,但题目要求算出最短的时间,那么我们就必须尽可能增加自己的步伐,但最后又必须为一步。
题目中说每一步的大小可以与前一步相等,或者比前一步小和大1。如果我们最开始按照递增的步伐进行走,就会出现一个步伐的峰值,到达这个峰值后就必须递减,保证最后一步的大小为1。通过一些数据分析,我们可以将次过程转换为如果是奇数步,那么下一步的步的大小保持不变,如果是偶数步,则下一步的大小+1,这样当总的步数大于两点距离的时候,循环终止,输出走的步数。
代码:
#include<iostream>
using namespace std;
int main()
{
int t,x,y;
cin>>t;
while(t--)
{
int dis,i,p,s;
cin>>x>>y;
dis=y-x;
if(dis==0)
cout<<"0"<<endl;
else
{
s=0;
i=1;
p=1;
for(;;)
{
s+=p;
if(s>=dis)
break;
if(i%2==0)
{
p++;
}
i++;
}
cout<<i<<endl;
}
}
return 0;
}