bzoj 1734: [Usaco2005 feb]Aggressive cows 愤怒的牛【二分+贪心】
二分答案,贪心判定
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=100005;
int n,m,a[N];
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
bool ok(int w)
{
int tot=1,pr=1,la=1;
while(tot<=m)
{
while(a[pr]-a[la]<w&&pr<=n)
pr++;
if(pr>n&&tot<m)
return 0;
tot++,la=pr;
}
return 1;
}
int main()
{
n=read(),m=read();
for(int i=1;i<=n;i++)
a[i]=read();
sort(a+1,a+1+n);
int l=1,r=1e9,ans=0;
while(l<=r)
{
int mid=(l+r)>>1;
if(ok(mid))
l=mid+1,ans=mid;
else
r=mid-1;
}
printf("%d\n",ans);
return 0;
}