POJ - 3273

Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ M≤ N) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.

FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.

Input

Line 1: Two space-separated integers: N and M 
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

Sample Input

7 5
100
400
300
100
500
101
400

Sample Output

500

 

 

#include <iostream>
#include <cstring>
#include <algorithm>
#include<cmath>
#include<stdio.h>
#include<queue>

using namespace std;
const int maxn=100010;
int sum[maxn],n,m;
bool solve(int s)
{
    int ss=0,group=1;
    for(int i=0;i<n;i++){
        if(ss+sum[i]<=s){
            ss+=sum[i];
        }
        else {
            group++;
            ss=sum[i];
        }
    }
    if(group>m){
        return false;
    }
    else return true;
}
int main()
{
    while(scanf("%d %d",&n,&m)!=EOF){
        int high=0,low=0;
        for(int i=0;i<n;i++){
            scanf("%d",&sum[i]);
            high+=sum[i];
            low=max(low,sum[i]);
        }
        int mid=(high+low)/2;
        while(high>low){
            if(!solve(mid)){
                low=mid+1;
            }
            else high=mid-1;
            mid=(high+low)/2;
        }
        cout<<mid<<endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章