hdu 4190 Distributing Ballot Boxes (二分)

来源:互联网 发布:手机撒谎软件安卓版 编辑:程序博客网 时间:2024/04/30 03:30

一看到题目中间的那句“minimizes the maximum number”就想到了二分法。。。一般这种“最大值最小” 和”最小值最大“都能二分搞!

ok(x)函数就是给定一个最大值x,挨个城市模拟分配box,维护每个box的人数不大于x,看能否在B个box内将其装好。

#include<cstdio>#include<algorithm>#include<iostream>using namespace std;int n, B, a[555555];bool ok(int x){    int num = B;    for(int i=0; i<n; i++)    {        if(a[i] <= x)   num--;        else        {            int tmp = a[i];            while(tmp > 0)            {                tmp -= x;                num--;            }        }    }    return num >= 0;}int main(){    while(scanf("%d%d", &n, &B) && n != -1 && B != -1)    {        int limit = 0;        for(int i=0; i<n; i++)        {            scanf("%d", &a[i]);            limit = max(limit, a[i]);        }        int L = 0, R = limit, M;        while(L < R)        {            M = (L + R) >> 1;            if(ok(M))   R = M;            else    L = M + 1;        }        printf("%d\n", R);    }}


原创粉丝点击