CodeForces - 11B Jumping Jack【数学】

【题目描述】
Jack is working on his jumping skills recently. Currently he’s located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he’ll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach x.

【输入】
The input data consists of only one integer x ( - 109 ≤ x ≤ 109).

【输出】
Output the minimal number of jumps that Jack requires to reach x.

【样例输入】
2

【样例输出】
3

【样例输入】
6

【样例输出】
3

【样例输入】
0

【样例输出】
0

题目链接:https://codeforces.com/contest/11/problem/B

非常有意思的一道数学题,从代码上来看非常的简单
但是并不是特别好想

首先,显然正的x和负的x由对称性可知一定是等价的,故只考虑正向的x。
要使跳跃次数最少,即一路向x跳,直到超过为止。
由于每次跳跃的长度都加一,一次向前接一次向后等效于向后移动一步。
考虑第一次超过x的位置y,1到y-x的所有数一定是所有跳跃长度的子集。
当y-x为偶数时,(y-x)/2一定为整数,且一定在向前跳跃长度的集合中,若将这一步改为向后跳跃,那么最终y-(y-x)/2-(y-x)/2=x,即跳跃到x和跳跃到y的步数是相等的,只是改变了其中一步的方向;当y-x为奇数时,那么继续跳下去,直到y与x的差为偶数时结束。

代码如下:

#include <iostream>
using namespace std;
int main()
{
    int x;
    cin>>x;
    if(x<0) x=-x;
    int cnt=0,y=0;
    while(y<x || (y-x)%2)
    {
        cnt++;
        y+=cnt;
    }
    cout<<cnt<<endl;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值