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;
}