首页 > 其他 > 详细

poj3273

时间:2014-01-20 23:07:50      阅读:389      评论:0      收藏:0      [点我收藏+]

典型的二分,二分上限是组成一个组,花费是每月花费之和,下线是组成N个组,花费是他们中最大的。单调性容易证明,分成组越少,花费越高,分成组越多,花费越少,呈线性关系,故可以采用二分法求解单调函数极值(最值)。

#include <iostream>
#include <vector>

using namespace std;

bool judge(int N, int M, int mid, vector <int> a) {
	int sum = 0;
	int group = 1;
	for (int i = 0; i < N; i++) {
		if (sum + a[i] <= mid) {                             // sum from day 0 to day i, if the sum <= mid, it means they must be in one group
			sum += a[i];
		}
		else { // if sum from day 0 to day i-1, plus day i, is bigger than sum, then it should be divided in to two groups, day 1 to day i-1, day i.
			sum = a[i];
			group++;
		}
	}
	if (group > M) {
		return false;
	}
	else return true;
}

int main() {
	int N, M;
	vector <int> a;
	while (cin >> N >> M) {
		int max = 0, sum = 0;
		for (int i = 0; i < N; i++) { //max group->n group->with max upon money, min group->1 group with sum of money
			int temp;
			cin >> temp;
			a.push_back(temp);
			if (temp > max) {
				max = temp;
			}
			sum += temp;
		}
        
		int mid = (max + sum) >> 1;
		while (max < sum) {
			if (judge(N, M, mid, a)) {
				sum = mid - 1;
			}
			else max = mid + 1;
			mid = (sum + max) >> 1;
		}
		cout << mid << endl;
	}
}


poj3273

原文:http://blog.csdn.net/zhengnanlee/article/details/18444315

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!