CF-1445B Jumps

题意

初始时刻,你位于 (x) 轴上的 (0) 位置处,现在你要到达 (x(x>0)) 处,你可以通过跳跃的方式到达。在第 (k) 次跳跃,你可以选择向右跳跃 (k) 个单位距离,或者向左跳跃 (1) 个单位。求出到达 (x) 处的最少步数。

(1≤t≤1000,1≤x≤10^6)

分析

假设连续向右跳跃 (step) 后到达点 (pos=frac{(step+1)·step}{2}) 处,并且 (posleq x) 。如果 (x=pos) ,那么 (step) 就是答案。如果 (pos>x) ,此时也有 (frac{(step-1)step}{2}<x),那么考虑将其中一次向右跳跃改为向左,那么 (pos-step-1leq pos'leq pos-2),又因为有:(pos-step<x<pos) ,即只要 (pos-step<xleq pos-2),就可以通过替换跳跃步骤中的一步来达到目的,答案仍为 (step) 。因此,只需要特判一下 (x=pos-1) 的情况即可,答案为 (step+1)

总结:难度不大,但是很少会从这个角度去考虑问题。

代码

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t,x;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&x);
        int step=0;
        while(step*(step+1)<2*x)
            step++;
        if(step*(step+1)/2==x+1)
            step++;
        printf("%d
",step);
    }

    return 0;
}

原文地址:https://www.cnblogs.com/1024-xzx/p/14076289.html