codeforces 1455 B题(思维、规律)

B. Jumps
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output

Topic:

You are standing on the OX-axis at point 0 and you want to move to an integer point 𝑥>0.

You can make several jumps. Suppose you’re currently at point 𝑦 (𝑦 may be negative) and jump for the 𝑘-th time. You can:

either jump to the point 𝑦+𝑘
or jump to the point 𝑦−1.
What is the minimum number of jumps you need to reach the point 𝑥?

Input
The first line contains a single integer 𝑡 (1≤𝑡≤1000) — the number of test cases.

The first and only line of each test case contains the single integer 𝑥 (1≤𝑥≤106) — the destination point.

Output
For each test case, print the single integer — the minimum number of jumps to reach 𝑥. It can be proved that we can reach any integer point 𝑥.

Example:
在这里插入图片描述
在这里插入图片描述
Note:
In the first test case 𝑥=1, so you need only one jump: the 1-st jump from 0 to 0+1=1.

In the second test case 𝑥=2. You need at least three jumps:

the 1-st jump from 0 to 0+1=1;
the 2-nd jump from 1 to 1+2=3;
the 3-rd jump from 3 to 3−1=2;
Two jumps are not enough because these are the only possible variants:

the 1-st jump as −1 and the 2-nd one as −1 — you’ll reach 0−1−1=−2;
the 1-st jump as −1 and the 2-nd one as +2 — you’ll reach 0−1+2=1;
the 1-st jump as +1 and the 2-nd one as −1 — you’ll reach 0+1−1=0;
the 1-st jump as +1 and the 2-nd one as +2 — you’ll reach 0+1+2=3;
In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0+1+2=3.

In the fourth test case, you need three jumps: the 1-st one as −1, the 2-nd one as +2 and the 3-rd one as +3, so 0−1+2+3=4.

Mentality:
先假设一直相加:1+2+3+4+5+6+…+k=sum,
这时通过观察可以发现假如第一步我选择退后则总和为
-1+2+3+4…+k=sum-2,假设在第二步倒退,1-1+3+4+…+k=sum-3,依此类推,我们可以得出我们从一一直加直到>=n(题目的输入),如果刚好=n,答案为k,如果sum-1==n,答案为g+1,我们只有在最后一步倒退可得,步数+1,如果sum>n,答案为g,我们将之前某一步设为到退即可。

Code :

#include<stdio.h>

int main() {

    int t;
    scanf_s("%d", &t);
    while (t--) {
        int n;
        scanf_s("%d", &n);
        int sum = 0;
        int i;
        for (i = 1; i <= n; i++) {
            sum += i;
            if (sum >= n)
                break;
        }
        if (n == sum)                      //如果一直前进正好走到
            printf("%d\n", i);
        else if (sum - 1 == n)             //只要最后回退
            printf("%d\n", i + 1);
        else                               //在中间第i回退,即可到达k - i - 1处
            printf("%d\n", i);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值