POJ3273 Monthly Expense 二分搜索

        题目大意:N个数,将其划分成M部分,每一部分中的数的相对位置在原来的序列中不改变,意思是连续的,不能打乱顺序随意划分,并将每一部分中的数相加,给出一系列数,求:这M个部分中最大的和最小为多少。

        这题就是最小化最大值,可以套用二分搜索模型,设C(X):=划分中最大的和不大于X,至此用二分法搜索最小的X值。

#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>

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

int cost[100001];

bool CC(int x, int n, int m)
{
	int curmonths = 1;
	int curcost = 0;
	for (int i = 0; i < n; i++)
	{
		if (cost[i] > x)
		{
			return false;
		}
		if (curcost + cost[i] <= x)
		{
			curcost += cost[i];
		}
		else
		{
			curcost = cost[i];
			curmonths++;
		}
		if (curmonths > m)
		{
			return false;
		}
	}
	return true;
}

int main()
{
#ifdef _DEBUG
	freopen("d:\\in.txt", "r", stdin);
#endif
	int n, m;
	scanf("%d %d\n", &n, &m);
	for (int i = 0; i < n;i++)
	{
		scanf("%d\n", &cost[i]);
	}
	int l = 0;
	int r = n * 10000 + 1;
	while (r - l > 1)
	{
		int mid = (r + l) / 2;
		if (CC(mid, n, m))
		{
			r = mid;
		}
		else
			l = mid;
	}
	printf("%d\n", r);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值