POJ 3273-Monthly Expense 求分组和的最小的最大值【二分答案】

题目链接:http://poj.org/problem?id=3273

题目大意:
给出一个有n个数据的数组,将其分为连续的m份,找到一种分法,是的m份中最大一份总和最小

解题思路:直接在答案的区间内二分查找,找到符合条件的答案。

#include <cstdio>

int main()
{
    int n, m;
    while (scanf("%d %d", &n, &m) != EOF)
    {
        int i, j;
        int a[100010]; int left = 0, right = 0;
        for (i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            if (left < a[i])left = a[i];
            right += a[i];
        }                 //二分答案,答案的值必然为最大值~所有数的总和之间
        while (left < right)
        {
            int cnt = 0;
            int mid = (left + right) >> 1; int cost = 0;
            for (i = 0; i < n; i++)         //对所二分的答案进行判断,看其是否满足题目条件
            {
                if (cost + a[i] > mid)
                {
                    cost = a[i];
                    cnt++;
                }
                else
                    cost += a[i];
            }
            cnt++;
            if (cnt <= m)right = mid;
            else
                left = mid + 1;
        }
        printf("%d\n", right);
    }
    return 0;
}

2018-05-13

猜你喜欢

转载自www.cnblogs.com/00isok/p/9032157.html