1. 程式人生 > >二分(洛谷-P1182)

二分(洛谷-P1182)

#include<stdio.h>
#include<algorithm>
#include<iostream>

using namespace std;
int a[100005];
int n , m;
int high, low = 0;
bool check(int flag)
{
    int sum = 0 ;
    int cnt = 1;//第一段
    for(int i = 1 ; i <= n ; i ++)
    {
        sum += a[i];
        if(sum > flag)
        {
            cnt ++;
            sum = a[i];//每一段的開頭
        }
    }
    if(cnt > m)
        return true;
    else
        return false;
}
int main(void)
{
    cin>>n>>m;
    for(int i = 1 ; i <= n ; i ++)
    {
        cin>>a[i];
        low = max(low, a[i]);
        high += a[i];
    }
    while(low < high)
    {
        int mid = (low + high) / 2;
        if(check(mid))
        {
            low = mid + 1;
        }
        else
        {
            high = mid;
        }
    }
    cout<<low<<endl;
	return 0;
}