hdu5935 Car 貪心 卡精度

Car

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 393    Accepted Submission(s): 143


Problem Description
Ruins is driving a car to participating in a programming contest. As on a very tight schedule, he will drive the car without any slow down, so the speed of the car is non-decrease real number.

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.
 

Input
First line contains an integer T, which indicates the number of test cases.

Every test case begins with an integers N, which is the number of the recorded positions.

The second line contains N numbers a1a2aN, indicating the recorded positions.

Limits
1T100
1N105
0<ai109
ai<ai+1
 

Output
For every test case, you should output 'Case #x: y', where x indicates the case number and counts from 1 and y is the minimum time.
 

Sample Input
1 3 6 11 21
 

Sample Output
Case #1: 4
 


貪心策略,倒着看,從後往前,後面的速度儘可能的大,這樣才能保證總的時間最短

那麼就確定了最後一段的時間爲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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章