思路:首先,看到题目中“最大化最近的两头牛之间的距离”,我们就该想到二分答案,二分两头牛之间的距离。然后,我们就该思考,我们可以想到如下的伪代码:
bool check(int x){
int res=0;
for(?~n){
if(){
res++;
}
}
return res>=m;
}这时,有经验的就知道:这不是还要个变量,记录上一个分割点的位置吗?这边我建议直接存数字。我们可以直接把第一个房间给一只奶牛住,剩下的继续迭代,每当 ,就该更新答案,由此,我们便可得到以下代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,a[212345],l=1,r=0,ans=1e13;
bool check(int x){ //x是距离
int res=1,past=a[1]; //res是入住奶牛数量,past是上一个奶牛居住对应的位置
for(int i=2;i<=n;i++){
if(a[i]-past>=x){ //当距离达到x后
past=a[i];
res++;
}
}
return res>=m; //如果≥m就是可以住得下所有奶牛,反之不行
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+n+1); //保证单调性
r=a[n]-a[1];
while(l<=r){
int mid=l+r>>1; //二分距离
if(check(mid)){
l=mid+1;
ans=mid;
}
else r=mid-1;
}
cout<<ans;
return 0;
} 注意:
- 变量 存放的是数字,不是下标!
- 因为题目不保证 数组单调递增,所以我们要排序一下。