POJ_2456_Agressive_cows_(二分,最大化最小值)

描述


http://poj.org/problem?id=2456

有n个小屋,线性排列在不同位置,m头牛,每头牛占据一个小屋,求最近的两头牛之间距离的最大值.

Aggressive cows
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10095   Accepted: 4997

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.

Source

分析


二分.

最大化最小值.

C(x)表示使两头牛之间最小距离为x,问题转化为求满足C(x)的x的最大值.可知x<=(总长)/(c-1).那么1~(总长)/(c-1)二分求解即可.

 #include<cstdio>
#include<algorithm>
using std :: sort; const int maxn=;
int n,c;
int a[maxn]; void init()
{
scanf("%d%d",&n,&c);
for(int i=;i<=n;i++) scanf("%d",&a[i]);
sort(a+,a+n+);
} bool judge(int x)
{
int last=;
for(int i=;i<=c;i++)
{
int now=last+;
while(now<=n&&(a[now]-a[last]<x)) now++;
if(now>n) return false;
last=now;
}
return true;
} int bsearch(int x,int y)
{
while(x<y)
{
int m=x+(y-x+)/;
if(judge(m)) x=m;
else y=m-;
}
return x;
} void solve()
{
int INF=(a[n]-a[])/(c-);
printf("%d\n",bsearch(,INF));
} int main()
{
freopen("cow.in","r",stdin);
freopen("cow.out","w",stdout);
init();
solve();
fclose(stdin);
fclose(stdout);
return ;
}
上一篇:Mapreduce的文件和hbase共同输入


下一篇:判断2D平面内某点是否在某个旋转的矩形(OBB)内的算法