POJ 2456 Aggressive cows (二分)
Posted l999q
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 2456 Aggressive cows (二分)相关的知识,希望对你有一定的参考价值。
Description
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don‘t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
His C (2 <= C <= N) cows don‘t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 3 1 2 8 4 9
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
题目大意:
有N个隔间和C头牛 , 给出n个隔间的位置 ,把每头牛分到一个隔间 ,问怎么分才能使任意两头牛之间的最小距离尽可能的大,求这个最大的 最小距离。
解题思路:
显然,这是一个最小值最大的问题 ,先考虑二分是否可行 ,如果可行首选二分。
隔间的位置是无序的 ,我们先把隔间按位置从小到大进行排序,显然任意两头牛之间距离最小为0,最大为a[n-1]-a[0],我们在这个区间内二分求值。枚举每个mid,通过判断以这个值为最小距离是否能放下C头牛,然后不断缩小区间范围求得最优解。
#include<stdio.h> #include<algorithm> using namespace std; const int N = 100010; int a[N],n,m; int _is(int x) { int cnt=0,y=a[0]; for (int i=1; i<n; i++) if (a[i]-y>=x) { cnt++; y=a[i]; if (cnt+1==m) return 1; } return 0; } int main() { scanf("%d%d",&n,&m); for (int i=0; i<n; i++) scanf("%d",&a[i]); sort(a,a+n); int l=0,r=a[n-1]-a[0]; while(l<=r) { int mid =l+(r-l)/2; if ( _is(mid) ) l=mid+1; else r=mid-1; } if (!_is(l)) l--; printf("%d ",l); return 0; }
以上是关于POJ 2456 Aggressive cows (二分)的主要内容,如果未能解决你的问题,请参考以下文章
POJ 2456 Aggressive cows (二分 基础)