poj 3273 Monthly Expense

来源:互联网 发布:php erp 编辑:程序博客网 时间:2024/05/29 01:53

用二分,详细思路见注释。

#include <stdio.h>#include <stdlib.h>int a[100000+10];int main(){    int n,m,group,high=0,mid,low=0,sum,sum_max,t=0;    int i;    scanf("%d %d",&n,&m);     for(i=0; i<n; i++)    {        scanf("%d",&a[i]);        high+=a[i];//所有天数的花费和作为最大值,相当于只分成一个组        if(a[i]>low)            low=a[i];//花费最多的那一天的值作为最小值,相当于分成n组    }    while(low<high)//在low==high之前可能有分组情况为m的,但是不能保证值最小    {        group=1;        mid=(low+high)/2;        sum=0;        sum_max=0;        for(i=0; i<n; i++)        {            sum+=a[i];            if(sum>mid)            {                sum=a[i];                group++;            }        }        if(group<=m)            high=mid;        else            low=mid+1;    }    printf("%d\n",low);    return 0;}