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?

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 m,n個房間,m頭牛。依次輸入房間座標。如何分配房間使得每個牛直接的距離都儘量大,求滿足這個條件兩個牛房間距離的最小值

Solution:先對輸入的房間座標進行排序,然後二分查找即可。第一個房間先放一隻牛,a[f]爲上一頭牛所在房間座標 如果mid爲所求解 當且僅當a[i]-a[f]≥mid。如果滿足條件sum+1。如果sum大於等於m,說明mid小於所求解,更新l=mid。



#include <stdio.h>
#include <string.h>
#include <math.h>
#include<algorithm>
#include <iostream>
using namespace std;
const int N = 100010;
int a[N];
int n, m;

int judge(int mid)
{
    int f = 0;//f爲 上一頭牛 所在的房間號
    int sum = 1;//記錄房間總數
    for (int i = 1; i < n; i++)
    {
        if (a[i] - a[f] >= mid)//如果mid爲所求解 當且僅當a[i]-a[f]大於等於mid
        {
            f=i;
            sum++;
        }
        else continue;
    }
    if (sum >= m) return 1;
    else 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 = -1;
    int r = 1000000000;
    int ans;
    while (r - l >= 0)
    {
        int mid = (l + r) / 2;
        if (judge(mid) == 1)
        {
            ans = mid;
            l = mid;
        }
        else r = mid;
        if (r - l == 1) //終止條件
            break;
    }
    printf("%d\n", ans);
    return 0;
}
發佈了77 篇原創文章 · 獲贊 47 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章