POJ 3258 二分答案

http://poj.org/problem?id=3258

#include <cstdio>
#include <algorithm>
using namespace std;

#define N     50002

int L, n, m;
int rock[N];

int solve() {
    // rock[i] is the distance between the i-th 
    // rock and the (i+1)-th rock
    
    int hig = L, low = 0;
    while (low <= hig) {
        int mid = (low + hig) / 2;
        int tmp = rock[0];
        int rmv = 0;
        for (int i = 1; i <= n; i++) {
            if (tmp < mid) {
                tmp += rock[i];
                rmv++;
            } else tmp = rock[i];
        }
        if (tmp < mid) rmv++;
        if (rmv > m) hig = mid - 1;
        else low = mid + 1;
    }
    // loop invariant:
    // for x > hig, the number of rocks to be removed nrmv > m
    // for x < low, nrmv <= m
    //
    // when the loop terminates, low = hig + 1;
    // so hig should be the answer
    return hig;
}

int main() {
    scanf("%d%d%d", &L, &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &rock[i]);
    rock[0] = 0, rock[n+1] = L;
    sort(rock, rock + n + 1);
    for (int i = 0; i <= n; i++)
        rock[i] = rock[i+1] - rock[i];
    printf("%d\n", solve());
    return 0;
}

 

posted @ 2015-09-03 21:06  william-cheung  阅读(159)  评论(0编辑  收藏  举报