BZOJ 1639: [Usaco2007 Mar]Monthly Expense 月度开支【二分+贪心】

1639: [Usaco2007 Mar]Monthly Expense 月度开支

【题目描述】
传送门

【题解】

二分答案,然后贪心check就可以了。

代码如下

#include<cstdio>
using namespace std;
int n,m,Ans,a[100005];
bool check(int x){
    int Sum=0,Now=1;
    for(int i=1;i<=n;i++){
        if(a[i]>x) return 0;
        if(Sum+a[i]<=x) Sum+=a[i];else Now++,Sum=a[i];
    }
    return Now<=m;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("prob.in","r",stdin);
    freopen("prob.out","w",stdout);
    #endif
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int L=1,R=1e9,mid=(R+L)>>1;L<=R;mid=(R+L)>>1)
    if(check(mid)) Ans=mid,R=mid-1;else L=mid+1;
    printf("%d\n",Ans);
    return 0;
}
posted @ 2018-05-20 14:10  XSamsara  阅读(118)  评论(0编辑  收藏  举报