Monthly Expense(二分法)

http://poj.org/problem?id=3273

// File Name: poj3273.cpp
// Author: bo_jwolf
// Created Time: 2013年10月06日 星期日 22:25:49

#include<vector>
#include<list>
#include<map>
#include<set>
#include<deque>
#include<stack>
#include<bitset>
#include<algorithm>
#include<functional>
#include<numeric>
#include<utility>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<ctime>

using namespace std;
const int maxn = 100005;
int num[ maxn ];

int main(){
	int n, m;
	while( scanf( "%d%d", &n, &m ) != EOF ){
		int sum = 0, Max = -1;
		for( int i = 0; i < n; ++i ){
			scanf( "%d", &num[ i ] );
			sum += num[ i ];
			Max = max( Max, num[ i ] );
		}
		int l = Max, r = sum;
		while( l < r ){
			int mid = ( l + r ) / 2;
			int sum = 0, ans = 1;
			for( int i = 0; i < n; ++i ){
				if( sum + num[ i ] <= mid )
					sum += num[ i ];
				else
					sum = num[ i ], ans++;
				if( ans > m )
					break;
			}
			if( ans <= m )
				r = mid;
			else
				l = mid + 1;
		}
		printf( "%d\n", l );
	}
return 0;
}


你可能感兴趣的:(二分)