[ACM] POJ 3273 Monthly Expense (二分解决最小化最大值)
来源:互联网 发布:多个数最大公约数算法 编辑:程序博客网 时间:2024/05/18 08:47
Description
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.
Input
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Sample Input
7 5100400300100500101400
Sample Output
500
Hint
Source
题意为给定一个n个数组成的序列,划分为m个连续的区间,每个区间所有元素相加,得到m个和,m个和里面肯定有一个最大值,我们要求这个最大值尽可能的小。
用二分查找可以很好的解决这个问题。这类问题的框架为,找出下界left和上界right, while(left< right), 求出mid,看这个mid值是符合题意,继续二分。最后right即为答案。
本题中的下界为n个数中的最大值,因为这时候,是要划分为n个区间(即一个数一个区间),left是满足题意的n个区间和的最大值,上届为所有区间的和,因为这时候,是要划分为1个区间(所有的数都在一个区间里面), 1<=m<=n, 所以我们所要求的值肯定在 [left, right] 之间。对于每一个mid,遍历一遍n个数,看能划分为几个区间,如果划分的区间小于(或等于)给定的m,说明上界取大了, 那么 另 right=mid,否则另 left=mid+1.
代码:
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;const int maxn=100010;int money[maxn];int n,m;int main(){ scanf("%d%d",&n,&m); int left=-1,right=0; for(int i=1;i<=n;i++) { scanf("%d",&money[i]); if(left<money[i]) left=money[i]; right+=money[i]; } while(left<right) { int mid=(left+right)/2; int cnt=0; int cost=0; for(int i=1;i<=n;i++) { if(cost+money[i]>mid) { cnt++;//划分区间,不包括当前的money[i] cost=money[i]; } else cost+=money[i]; } cnt++;//最后一个cost值也要占一天 if(cnt<=m) right=mid; else left=mid+1; } cout<<right<<endl; return 0;}
- [ACM] POJ 3273 Monthly Expense (二分解决最小化最大值)
- [ACM] POJ 3273 Monthly Expense (二分解决最小化最大值)
- POJ 3273 Monthly Expense (二分,最小化最大值)
- poj 3273- Monthly Expense(最大值最小化)-二分
- POJ - 3273 Monthly Expense(二分搜索:最小化最大值)
- poj 3273 Monthly Expense (二分最小化最大值)
- POJ 3273 Monthly Expense【二分】(最大值最小化)
- POJ 3273 Monthly Expense(二分 最小化最大值)
- POJ 3273 Monthly Expense(二分,最大值最小化)
- poj 3273 Monthly Expense (二分搜索,最小化最大值)
- poj--3273 Monthly Expense(最小化最大值)
- poj Monthly Expense(最大值最小化)
- POJ 3273 Monthly Expense(区间和最大值最小-二分)
- Monthly Expense poj3273 (二分/最大值最小化)
- (最小化最大值)poj3273,Monthly Expense
- Monthly Expense (最大值最小化+二分法)
- POJ 3273 Monthly Expense(二分枚举)
- POJ 3273 - Monthly Expense(二分)
- 页面倒计时
- 并发控制____完成量(comletion)
- activity启动模式探究
- Solr 简介(一)
- I/O多路复用
- [ACM] POJ 3273 Monthly Expense (二分解决最小化最大值)
- ViewPager+Fragment+NumberPicker显示的问题
- Html 字体
- git常用命令
- MAC 10.X 安装Haskell的方法
- 2014可信软件系统工程(国际)暑期学校
- eclipse编译jsp中文出现乱码
- 第一篇博客
- 委托代理