[POJ 4135] Monthly Expense(二分法)

描述

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.

输入

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

输出

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

样例输入

7 5
100
400
300
100
500
101
400

输出

500

题解

#include <iostream>
#include <algorithm>
using namespace std;


int a[100005], n=0, m=0;
bool judge(int mid) {        
  int sum=0, t=0;                // sum为开销计数器,t为fajomonths计数器
  for (int i=0; i<n; i++) {      // sum一直累加,一旦超过猜测值,则开销a[i]为下个fajo月的
    if (sum+a[i] > mid) {         
      sum = a[i];                
      t++;
    }
    else sum += a[i];           
  }
  
  return t>=m;                   
}


int binarysearch(int l, int r) {
  int mid;
  do {
    mid = l + (r-l)/2;            // 防止溢出
    if (judge(mid)) l=mid+1;
    else r=mid-1;
  } while (l<=r);                 // 闭区间
  
  return mid;
}

int main() {
    int total=0, max=0;
    cin>>n>>m;
    for(int i=0;i<n;i++) {
        cin>>a[i];
        total+=a[i];            //记录开销的总和 
        if(max<a[i]) max=a[i];  //数组不能排序,记录开销的最大值
    }

    cout << binarysearch(max,total) << endl;        
    return 0;
}
发布了21 篇原创文章 · 获赞 8 · 访问量 1495

猜你喜欢

转载自blog.csdn.net/K_Xin/article/details/87864712
今日推荐