Go Home(AtCoder-2354)

Problem Description

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i−1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i−1 is x, he can be at coordinate x−i, x or x+i at time i. The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible. Find the earliest possible time to reach coordinate X.

Constraints

  • X is an integer.
  • 1≤X≤109

Input

The input is given from Standard Input in the following format:

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Example

Sample Input 1

6

Sample Output 1

3
The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2
He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5

题意:有一个人从起点 0 开始在路上直线行走,第 i 分钟可以走长度 i,其可以不走可以向左也可以向右,现在其要到达 x,问最少需要的时间

思路:

假设从起点开始一直向右走,走了 i 分钟,那么有两种情况:

  • 若第 i 分钟恰好走到 x,则此时的 i 为最理想的时间
  • 若第 i 分钟走到了 i 之后,且第 i-1 分钟走到了 i 之前,那么假设在第 i 次走到 x+dis,那么有 dis<x,因此可以选择在第 dis 次不向前走,从而使得在第 i 次正好到 x

因此,只需要维护一个前缀和数组,在在前缀和数组中查找第一个大于等于 x 的数字的位置即可

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {0,0,-1,1,-1,-1,1,1};
const int dy[] = {-1,1,0,0,-1,1,-1,1};
using namespace std;

int sum[N];
int main() {
    for(int i=1; i<=N-1; i++)
        sum[i]=sum[i-1]+i;

    int x;
    scanf("%d",&x);
    int left=1,right=N-1;
    while(left<=right){
        int mid=(left+right)/2;
        if(sum[mid]<x){
            left=mid+1;
        }
        else if(sum[mid]>=x){
            right=mid-1;
        }
    }
    int pos=right+1;
    printf("%d\n",pos);
    return 0;
}

 

posted @ 2022-09-20 22:54  老程序员111  阅读(8)  评论(0)    收藏  举报