Description
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 3 1 2 8 4 9
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
算法分析:使用二分+贪心算法。原始数据需要先排好序,使用快速排序。
#include <stdio.h>
#include <stdlib.h>
#define STALL_MAX_CNT 100000
static int g_stall[STALL_MAX_CNT];
static int g_cow_cnt;
static int g_stall_cnt;
int C(int d)
{
int cnt = 1;
int last = 0;
int current = 1;
while( current < g_stall_cnt)
{
if(g_stall[current] - g_stall[last] < d)
{
++current;
}
else
{
last = current;
++cnt;
if(cnt >= g_cow_cnt)
{
return 1;
}
}
}
return 0;
}
int solve(void)
{
int left = 0;
int right = g_stall[g_stall_cnt - 1];
while( left < right)
{
int mid = (right - left) / 2 + left;
if(C(mid))
{
left = mid + 1;
}
else
{
right = mid;
}
}
return left - 1;
}
void insert_sort(int *a, int s, int e)
{
int i, j;
for(i = s + 1; i <= e; ++i)
{
j = i-1;
int k = a[i];
while( j >= s && a[j] > k)
{
a[j+1] = a[j];
--j;
}
a[j+1] =k;
}
}
int g_cutoff = 10;
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int median_of_three(int *a, int s, int e)
{
int mid = (e -s ) / 2 + s;
if(a[s] > a[mid])
{
swap(&a[s], &a[mid]);
}
if(a[s] > a[e])
{
swap(&a[s], &a[e]);
}
if(a[mid] > a[e])
{
swap(&a[mid], &a[e]);
}
swap(&a[mid], &a[e-1]);
return a[e-1];
}
void quick_sort_core(int *a, int s, int e)
{
if(s + g_cutoff <= e)
{
int pivot = median_of_three(a, s, e);
int i = s;
int j = e -1;
while(1)
{
while(a[++i] < pivot);
while(a[--j] > pivot);
if(i < j)
{
swap(&a[i], &a[j]);
}
else
{
break;
}
}
swap(&a[i], &a[e-1]);
quick_sort_core(a, s, i-1);
quick_sort_core(a, i+1, e);
}
else
{
insert_sort(a, s, e);
}
}
void quick_sort(int *a, int size)
{
quick_sort_core(a, 0, size -1);
}
int main(void)
{
scanf("%d %d", &g_stall_cnt, &g_cow_cnt);
int i;
for(i = 0; i < g_stall_cnt; ++i)
{
scanf("%d", &g_stall[i]);
}
quick_sort(g_stall, g_stall_cnt - 1);
int ret = solve();
printf("%d\n", ret);
return 0;
}
二分函数也可以这样写:
int solve(void)
{
int left = 0;
int right = g_stall[g_stall_cnt - 1];
while( left <= right)
{
int mid = (right - left) / 2 + left;
if(C(mid))
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return left - 1;
}