题解:P1824 [USACO05FEB] 进击的奶牛 Aggressive Cows G
思路:首先,看到题目中“最大化最近的两头牛之间的距离”,我们就该想到二分答案,二分两头牛之间的距离。然后,我们就该思考
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;
}
注意:
- 变量
past 存放的是数字,不是下标! - 因为题目不保证
x 数组单调递增,所以我们要排序一下。