首页 > 代码库 > POJ 3258 River Hopscotch
POJ 3258 River Hopscotch
Description
Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully jumping from rock to rock in a river. The excitement takes place on a long, straight river with a rock at the start and another rock at the end, L units away from the start (1 ≤ L ≤ 1,000,000,000). Along the river between the starting and ending rocks, N (0 ≤ N ≤ 50,000) more rocks appear, each at an integral distance Di from the start (0 < Di <L).
To play the game, each cow in turn starts at the starting rock and tries to reach the finish at the ending rock, jumping only from rock to rock. Of course, less agile cows never make it to the final rock, ending up instead in the river.
Farmer John is proud of his cows and watches this event each year. But as time goes by, he tires of watching the timid cows of the other farmers limp across the short distances between rocks placed too closely together. He plans to remove several rocks in order to increase the shortest distance a cow will have to jump to reach the end. He knows he cannot remove the starting and ending rocks, but he calculates that he has enough resources to remove up to M rocks (0 ≤ M ≤ N).
FJ wants to know exactly how much he can increase the shortest distance *before* he starts removing the rocks. Help Farmer John determine the greatest possible shortest distance a cow has to jump after removing the optimal set of M rocks.
Input
Lines 2..N+1: Each line contains a single integer indicating how far some rock is away from the starting rock. No two rocks share the same position.
Output
Sample Input
25 5 2214112117
Sample Output
4
二分法:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int comp(const void *a,const void *b); 5 int Try(int D); 6 int a[50005]; 7 int N,M; 8 9 int comp(const void *a,const void *b)10 {11 return *(int *)a-*(int *)b;12 }13 14 int Try(int D)15 {16 int i, t, n;17 for (n=0, t=0, i=0; i<N; i++)18 {19 t += a[i];20 if (t<D) n++;21 else t=0;22 }23 if (t + a[N] < D) n++;24 if (n > M) return 0;25 else return 1;26 }int main()27 {28 int H, L, D, i;29 scanf("%d%d%d",&H, &N, &M);30 for (i = 1; i <= N; i++)31 scanf("%d", &a[i]);32 qsort(a, N+1, sizeof(int), comp);33 a[N+1] = L = H;34 for (i=0; i <= N; i++)35 {36 a[i] = a[i+1] - a[i];37 if (a[i] < L) L = a[i];38 }39 while (H - L > 1)40 {41 D = ( H + L)/2;42 if (Try(D))43 L = D;44 else H = D;45 }46 D = L;47 if (Try(D+1))48 D++;49 printf("%d", D);50 return 0;51 }