3613 - 步数
时间限制 : 2 秒
内存限制 : 128 MB
给出两个处在x轴的点的坐标,从一个朝另一个出发,第一步只能走一个单位
以后每一步可以走的单位数可以是等于前一步,可以是少于前一步,可以是大于前一步。
但最后一步只能走一个单位。
问题是,求出最少的步数。
两点的坐标分别为x1,x2 0<=x1<=x2<=2^31.
题目输入
每一行输入x1,x2。
题目输出
每一行输出最小的步数。
输入/输出样例
输入格式
45 48 45 49 45 50
输出格式
3 3 4
C语言解答
#include <stdio.h> int main() { int n1,n2,num,i,step; while(scanf("%d%d",&n1,&n2)!=EOF) { num=n2-n1; i=1; step=0; if(num==0) printf("%d\n",num); else while(1) { num-=i; step++; if(num<=0) { printf("%d\n",step); break; } num-=i; step++; if(num<=0) { printf("%d\n",step); break; } i++; } } return 0; }
C++解答
#include <bits/stdc++.h> using namespace std; int main() { long long x1,x2; while(~scanf("%lld%lld",&x1,&x2)){ long long cha=x2-x1; long long step=0; if (cha==0){ printf("0\n"); continue; } while((step*step)<=cha){ step++; } /* prlong longf("%lld\n",step*0); prlong longf("%lld\n",step*1); prlong longf("%lld\n",step*2); */ if (cha- (step*step) >=0){ cha -= (step*step); } else{ step--; cha -= (step*step); } if (cha==0){ printf("%lld\n",step*2-1); continue; } long long ans=step; if (cha%step>0){ ans+=((cha/step)+1); } else ans+=(cha/step); if (step>1) ans+=step-1; printf("%lld\n",ans); } return 0; }