1. 程式人生 > >POJ 2456 Aggressive cows (二分)

POJ 2456 Aggressive cows (二分)

Once cati and res cat -a isp ive pen

題目傳送門 POJ 2456

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?

Input

* Line 1: Two space-separated integers: N and C

* 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. 題目大意:
  有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\n",l); return 0; }
View Code

POJ 2456 Aggressive cows (二分)