C - Go Home
Time limit : 2sec / Memory limit : 256MB
Score : 200 points
Problem Statement
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
思路:題解很簡單一句話:The answer is the minimum t such that 1 + 2 + ... + t ≥ X.比賽時我也是按照這個思路寫的,什麼意思呢?
如果前t分鐘一直向左走,加起來的路程如果恰好等於x,那一定就是時間t最短。
可如果超過了呢?超過的距離是d,那麼滿足 d < sum(t+1) - sum(t),d就是[0, t]之間的數,0的情況說了沒問題。
不是0呢,不論多了幾,肯定是之前出現的某個距離,根據d的範圍就知道了,那就之前那個距離的時候不走,這多出
的距離不就可以減去了嗎。所以這樣答案也是成立的。這樣就對了。
#include <bits/stdc++.h>
const int N = 44721;
using namespace std;
int sum[N];
int main()
{
for (int i = 1; i <= N; i++)
{
sum[i] = sum[i-1] + i;
}
int x;
while (~scanf("%d", &x))
{
int loc = lower_bound(sum, sum + N, x) - sum;
printf("%d\n", loc);
}
return 0;
}