B. Jumps(模拟)

B. Jumps
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are standing on the OX-axis at point 0 and you want to move to an integer point x>0.

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

either jump to the point y+k
or jump to the point y−1.
What is the minimum number of jumps you need to reach the point x?

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

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

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

Example
inputCopy
5
1
2
3
4
5
outputCopy
1
3
2
3
4
Note
In the first test case x=1, so you need only one jump: the 1-st jump from 0 to 0+1=1.

In the second test case x=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.

题意:
0 0 0点开始走
k k k步你可以有两种选择:

  1. 向前走 k k k步 +k
  2. 向后走 1 1 1步 -1
    问你走到 n n n时最少走多少步?

题解:
其实很简单的模拟,假设每次都往前走那么就是 1 + 2 + 3 + 4..... + x = y 1+2+3+4.....+x=y 1+2+3+4.....+x=y就是 y = ( n + 1 ) ∗ n / 2 y=(n+1)*n/2 y=(n+1)n/2
那么我们要走到 y-2我们就可以将 + 1 +1 +1改成 − 1 -1 1
走到 y − 3 y-3 y3我们就可以将 + 2 +2 +2改成 − 1 -1 1

走到 y − x + 1 y-x+1 yx+1我们就可以将 + ( x − 2 ) +(x-2) +(x2)改成 − 1 -1 1
其实就是在 y y y上减去变化的步数 z z z并且把他改成 − 1 -1 1还要减 1 1 1,所以我们最小就要减去 2 2 2。对于 y − 1 y-1 y1我们只能让他在到 y y y后退一步了。

所以我们就推出,
(1). 如果 ( n + 1 ) ∗ n / 2 = y (n+1)*n/2=y (n+1)n/2=y 那么就是走 n n n
(2). 如果 ( n + 1 ) ∗ n / 2 = y + 1 (n+1)*n/2=y+1 (n+1)n/2=y+1那么就是走 n n n步再往后退一格 也就是 n + 1 n+1 n+1步。
(3). 其他其实就是跟我们分析的一样 走 n n n步。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n;
ll sum;
ll dp[1000100];
string str;
int main() {
    
    
    int t;
    cin>>t;

    while(t--) {
    
    
        cin>>n;
        int i = 1;
        for(; i * (i + 1) / 2 < n; i ++);
        sum = i * (i + 1) / 2;
        if(sum == n) {
    
    
            cout << i << endl;
        } else if(sum == n + 1) {
    
    
            cout << i + 1 << endl;
        } else cout << i << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45911397/article/details/110528296