题解:P1824 [USACO05FEB] 进击的奶牛 Aggressive Cows G
huanghao2024 · · 题解
P1824 [USACO05FEB] 进击的奶牛 Aggressive Cows G
Solution
二分板子题。
二分任意两头牛之间的最小距离 check 函数来判断奶牛两两距离最小为
现在来考虑 check 函数的写法。这里可以使用贪心,循环遍历所有牛棚,如果当前奶牛与上一只奶牛的距离差小于
时间复杂度为
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
int n,m,k[N],ans;
bool check(int a)
{
int last=1,sum=1;
for(int i=2;i<=n;i++)
if(k[i-1]-k[last-1]>=a) last=i,sum++;
return sum>=m;
}
signed main()
{
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>k[i-1];
sort(k,k+n);
int l=0,r=1e9+10;
while(l<r)
{
int middle=(l+r+1)>>1;
if(check(middle)) ans=middle,l=middle;
else r=middle-1;
}
cout<<ans<<endl;
return 0;
}