Codeforces11B. 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.

Input
The input data consists of only one integer x ( - 109 ≤ x ≤ 109).

Output
Output the minimal number of jumps that Jack requires to reach x.

Examples
inputCopy
2
outputCopy
3
inputCopy
6
outputCopy
3
inputCopy
0
outputCopy
0

题意:
起点为0,终点为x。第一次只能走一步,后面每次走的步数比前面多1。可以往左可以往右,求最小步数走到x。

思路:
首先不妨设x为正数(负数则取绝对值),那么直观的想法就是能往右走就往右走,这样能尽量节省步数。

但是这样不一定刚好凑得出x,最后一步可能会溢出。

考虑溢出的部分,假设为y。

  1. 如果y为偶数,那么只要将第y/2步设置成往左走,就可以抵消溢出贡献了。
  2. 如果y为奇数,但是下一步的步数如果是奇数,那么再加上下一步溢出值就成了偶数了,这时候同1的操作。
  3. 如果y为奇数,但是下一步的步数如果是偶数,那么我们只需要再加上后面两步,并使得后面第一步向左,第二步向右,这样溢出值刚好多1,溢出值就又成了偶数了,同1操作。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
 
using namespace std;
 
typedef long long ll;
 
int vis[100005];
int main() {
    int x;scanf("%d",&x);
    int ans = 0;
    x = abs(x);
    for(int i = 1;i <= x;i++) {
        int num = (1 + i) * i / 2;
        if(num >= x) {
            ans = i;
            if((num - x) % 2 != 0) {
                if((i + 1) % 2 == 1) {
                    ans++;
                } else {
                    ans += 2;
                }
            }
            break;
        }
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/108359594
今日推荐