Car
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 393 Accepted Submission(s): 143
Of course, his speeding caught the attention of the traffic police. Police record N positions of Ruins without time mark, the only thing they know is every position is recorded at an integer time point and Ruins started at 0.
Now they want to know the minimum time that Ruins used to pass the last position.
Every test case begins with an integers N, which is the number of the recorded positions.
The second line contains N numbers a1, a2, ⋯, aN, indicating the recorded positions.
Limits
1≤T≤100
1≤N≤105
0<ai≤109
ai<ai+1
貪心策略,倒着看,從後往前,後面的速度儘可能的大,這樣才能保證總的時間最短
那麼就確定了最後一段的時間爲1,這樣最後一段的速度就最大化了,把這個速度往前面傳,用前一段距離除以後一段速度,得到時間,如果得到的時間不是整數,要向上取整(因爲要保證前面的速度比後面的速度小),然後再用這個時間算當前段的實際速度,繼續把新的速度往前面傳……
本來想用double表示速度,ceil向上取整,結果WA,可能是精度損失,換成分數就過了,真坑
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
int T, n, kase, ans, t;
int a[100005];
int main()
{
cin >> T;
kase = 0;
while (T--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
a[0] = 0;
ll fenzi, fenmu;
ans = 0;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
t = 1;
fenzi = a[i + 1] - a[i];
fenmu = 1;
ans += t;
}
else {
int dis = a[i + 1] - a[i];
fenmu *= dis;
swap(fenmu, fenzi);
if (fenzi % fenmu) {
t = fenzi / fenmu + 1;
}
else {
t = fenzi / fenmu;
}
ans += t;
fenzi = a[i + 1] - a[i];
fenmu = t;
}
}
printf("Case #%d: %d\n", ++kase, ans);
}
return 0;
}