POJ 3273 二分
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 5 100 400 300 100 500 101 400
Sample Output
500
Hint
If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.
题目大意:
给出农夫在n天中每天的花费,要求把这n天分作m组,每组的天数必然是连续的,要求分得各组的花费之和应该尽可能地小,最后输出各组花费之和中的最大值。最大化最小值即可,二分搜索。
下见代码:
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> using namespace std; const int maxn=100005; int n,m; int a[maxn]; bool C(int x) //c(x)=能不能把n个数分成最多m个每个组的和不超过x的组。(有点绕,但这是重点,仔细理解) { int sum=0; int num=1; for(int i=0;i<n;i++) { sum+=a[i]; if(sum>x) { sum=a[i]; num++; } } return num<=m; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { int MAX=0; int asum=0; for(int i=0;i<n;i++) { scanf("%d",&a[i]); MAX=max(MAX,a[i]); asum+=a[i]; } int lb=MAX,ub=asum,ans=0; while(lb<=ub) { int mid=(lb+ub)/2; if(C(mid)) { ans=mid; ub=mid-1; } else lb=mid+1; } printf("%d\n",ans); } return 0; }
做人要厚道,转帖请注明出处!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步