首页 > 代码库 > POJ 3273 Monthly Expense 二分答案
POJ 3273 Monthly Expense 二分答案
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 13281 | Accepted: 5362 |
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
题解
又是一个二分题。题目的意思是说,在接下来的n天里,Farmer John每天需要花money[i]钱,把这些天分成k份(每份都是连续的天),要求每份的和尽量少,输出这个最小的和。
依旧是二分答案二分答案。。。但是特别奇怪,如果用一个res维护当前可行值就会WA,而且R也得用r = mid 而不是r = mid - 1。。。
这个二分真是难
代码示例
/**** *@author Shen *@title poj 3273 */ #include <cstdio> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int n, k; int r, v[100005]; int maxa = 0, mina = 0; bool test(int x) { int sum = 0, cnt = 1; for (int i = 0; i < n; i++) { if (sum + v[i] <= x) sum += v[i]; else cnt++, sum = v[i]; } //printf("\t%s with x = %d, result is that sum = %d.\n", __func__, x, sum); return cnt <= k; } int Bsearch(int l, int r) { while (l < r) { int mid = (r + l) / 2; //printf("l = %d, r = %d, mid = %d.\n", l, r, mid); if (test(mid)) r = mid; else l = mid + 1; } return l; } void solve() { maxa = mina = 0; for (int i = 0; i < n; i++) { scanf("%d", &v[i]); maxa += v[i]; mina = max(mina, v[i]); } int ans = Bsearch(mina, maxa); printf("%d\n", ans); } int main() { while (~scanf("%d%d", &n, &k)) solve(); return 0; }