POJ3273-Monthly Expense-二分答案

FJ对以后的每一天会花mi块钱,他想把这些天分成M个时段,然后每个时段的花费和最小。

二分答案,如果加上这天还没有达到mid,就加上它。之后看分成的时段是否大于M

#include <cstdio>
#include <algorithm>

using namespace std;

int n,m,money[100100];

int judge(int mid)
{
    int group = 1,sum = 0;
    for(int i=0;i<n;i++)
    {
        if(sum+money[i] <= mid)
        {
            sum += money[i];
        }
        else
        {
            group++;
            sum = money[i];
        }
    }

    if(group > m)
        return false;
    else
        return true;
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        int low=0,high=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&money[i]);
            high += money[i];
            low = max(low,money[i]);
        }
        int mid = (low+high)/2;

        while(low < high)
        {
            if(!judge(mid))
                low = mid+1;
            else high = mid-1;

            mid = (low+high)/2;
        }
        printf("%d\n",mid);
    }
}

 

你可能感兴趣的:(POJ3273-Monthly Expense-二分答案)