POJ 2456 Aggressive cows(二分-最大化最小值)
阿新 • • 發佈:2019-02-01
Description
農夫約翰搭了一間有N間牛舍的小屋。牛舍排在一條直線上,第i號牛舍在xi的位置。但是他的M頭牛對小屋很不滿意,因此經常相互攻擊。約翰為了防止牛之間相互傷害,因此決定把每頭牛都放在離其他牛儘可能遠的牛舍。也就是說要最大化最近的兩頭牛之間的距離
Input
第一行兩個整數N和M表示牛舍數和牛數,之後N行每行一個整數表示牛舍位置
Output
輸出兩頭牛之間距離的最大值
Sample Input
5 3
1
2
8
4
9
Sample Output
3
Solution
最大化最小值,二分距離即可
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 100000
#define INF 1000000000
int N,M;
int x[maxn];
bool C(int d)//判斷是否滿足條件
{
int last=0;
for(int i=1;i<M;i++)
{
int crt=last+1;
while(crt<N&&x[crt]-x[last]<d)
{
crt++;
}
if (crt==N)
return false;
last=crt;
}
return true;
}
int main()
{
scanf("%d%d",&N,&M);
for(int i=0;i<N;i++)
scanf("%d",&x[i]);
sort(x,x+N);//將牛舍位置排序
int lb=0,ub=INF;//初始化解的存在範圍
while(ub-lb>1)
{
int mid=(lb+ub)/2;
if (C(mid))
lb=mid;
else
ub=mid;
}
printf("%d\n",lb);
return 0;
}