POJ 2456 (二分找值)

題意:

給定num_place([2, 10^5])個牛欄
每個牛欄的位置爲xi([0, 10^9])
有num_cow([2, num_place])個牛需安排在牛欄裏,求安排後牛之間最小值的最大值。


思路:

值域在[0, 10^9]之間,最優值爲可以容納下的方案的最大值

可用二分枚舉+驗證縮小值域直至得出結果。


#include <iostream>
#include <stdio.h>
#include <algorithm>
#define INF 1e9

using namespace std;

int place[100100];  // the position of cow
int num_place;
int num_cow;

bool check(int diff)
{
    int cnt = 1;
    int last = place[0];
    for (int i = 1; i < num_place; ++i)
    {
        if(cnt == num_cow)
            break;
        if(place[i] >= last + diff)
        {
            cnt++;
            last = place[i];
        }
    }
    if(cnt == num_cow)
        return true;
    else
        return false;
}

int solve()
{
    int l = 0;
    int r = INF+1; // find in [l, r)
    while(l+1<r)
    {
        int mid = (r - l)/2 + l;
        if(check(mid))
            l = mid;
        else
            r = mid;
    }
    return l;
}

int main()
{
    cin>>num_place>>num_cow;

    for (int i = 0; i < num_place; ++i)
        scanf("%d", &place[i]);

    sort(place, place+num_place); // from low to high

    cout<<solve()<<endl;
}


發佈了30 篇原創文章 · 獲贊 0 · 訪問量 9154
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章