poj2456

二分法

有些能用动态规划求解但是超时的题目,可以考虑二分法。

View Code
#include <iostream>

#include <cstdio>

#include <cstdlib>

#include <cstring>

#include <algorithm>

using namespace std;



#define maxn 100005

#define inf 0x3f3f3f3f



int n, cow;

int pos[maxn];



void input()

{

    scanf("%d%d", &n, &cow);

    for (int i = 0; i < n; i++)

        scanf("%d", &pos[i]);

}



bool ok(int len)

{

    int l = 0, r = 0;

    for (int i = 1; i < cow; i++)

    {

        while (r < n && pos[r] - pos[l] < len)

            r++;

        if (r >= n)

            return false;

        l = r;

    }

    return true;

}



int binary_search()

{

    int l = inf;

    for (int i = 1; i < n; i++)

        l = min(l, pos[i] - pos[i - 1]);

    int r = (pos[n - 1] - pos[0]) / (cow - 1);

    while (l < r)

    {

        int mid = (l + r) / 2 + ((l + r) & 1);

        if (!ok(mid))

            r = mid - 1;

        else

            l = mid;

    }

    return l;

}



int main()

{

    //freopen("t.txt", "r", stdin);

    input();

    sort(pos, pos + n);

    printf("%d\n", binary_search());

    return 0;

}

你可能感兴趣的:(poj)