跳到正文

题解

题解:P1824 [USACO05FEB] 进击的奶牛 Aggressive Cows G

Alen_0501约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年12月28日
收录
2026年9月12日
更新
2026年11月8日
篇幅
约 2 分钟
获赞
1
题目
P1824

版本

  1. v1当前

思路:首先,看到题目中“最大化最近的两头牛之间的距离”,我们就该想到二分答案,二分两头牛之间的距离。然后,我们就该思考checkcheck,我们可以想到如下的伪代码:

C++
bool check(int x){
    int res=0;
    for(?~n){
        if(){
           res++;
        }
    }
    return res>=m;
}

这时,有经验的就知道:这不是还要个变量pastpast,记录上一个分割点的位置吗?这边我建议直接pastpast存数字。我们可以直接把第一个房间给一只奶牛住,剩下的继续迭代,每当 ai−past≥xa_i - past ≥ x ,就该更新答案,由此,我们便可得到以下代码:

C++
#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;
} 

注意:

  1. 变量pastpast 存放的是数字,不是下标!
  2. 因为题目不保证 xx 数组单调递增,所以我们要排序一下。
原文