您的位置:首页 > 其它

cf#11-B - Jumping Jack-数学

2016-01-29 00:20 176 查看
http://codeforces.com/contest/11/problem/B

Jack在数轴上跳。他第i次跳可以往左或往右跳i个单位。现在问你他最少花多少步跳到点x。
-x的答案显然和x一样,0特判

首先我们让jack跳到第一个大于等于x的地方,走了K步,如果等于,显然结束算法。

如果是大于,我们计算res=当前位置-x,如果res为偶数,显然只要我们之前再步数=res/2的时候,往左跳一步,那么的最后的位置就会比当前少res长度,也就是恰好到达 位置X,总步数K。

如果res为奇数,  那么需要再走多奇数步,凑一个偶数出来, 如果当前步数为偶数,那么下一步就是奇数,只要再走多一步,就回到上面的情况了,总步数K+1。

如果当前步数为奇数,那么只要走多两步即可回到最上面的情况,总步数K+2

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
__int64 x;
scanf("%I64d",&x);

if (!x)
{ printf("0\n");return 0;}
if (x<0) x=-x;
__int64 tmp=0;
__int64 ans=1;
while(tmp<x) { tmp+=ans;ans++;}

ans--;

//ans为第一个大于等于与x的数
__int64 res=ans*(ans+1)/2-x ;
if (res==0)
printf("%I64d\n",ans);
else
{

if (res%2==0)
printf("%I64d\n",ans);
else
{
if (ans%2) ans++;
printf("%I64d\n",ans+1);
}
}
return 0;

}
//57283
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: