POJ 3273Monthly Expense (二分,最小值)

题目大意是求给出的N个数分成连续的M组, 求组内数之和的最小值。

发现二分循环里最后输出mid比较保险。。一开始输出了l总是错

 

题目:

Monthly Expense
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 11653   Accepted: 4769

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 ≤ MN) 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

Line 1: Two space-separated integers: N and M
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

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.

Source

 
 
代码:
POJ 3273Monthly Expense (二分,最小值)
 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 #define MAXN 100000+100
 5 #define min(x,y)  x<y?x:y
 6 int N,M;
 7 int cost[MAXN];
 8 
 9 bool C(int x)
10 {
11     int n = 1;
12    // cout<<x<<endl;
13     int tmp =0;
14     for(int s = 0; s<N;s++)
15     {
16             if( tmp+cost[s]<=x)
17             {
18                 tmp+=cost[s];
19             }
20             else
21             {
22                     n++;
23                     tmp = cost[s];
24             }
25     }
26     if( n>M)return false;
27 
28     else return true;
29 }
30 
31 
32 int main()
33 {
34     while(cin>>N>>M)
35     {
36         int l = 0 , r=0;
37         for(int i=0;i<N;i++)
38         {
39             cin>>cost[i];
40             r+= cost[i];
41             l = max(cost[i],l);
42         }
43          int mid = l+(r-l)/2;
44         while( l<r)
45         {
46 
47         //cout<<l<<" "<<r<<endl;
48             if( C(mid) ) r= mid-1;
49             else
50                 l = mid+1;
51             mid = l+(r-l)/2;
52         //cout<<mid<<endl;
53         }
54         cout<<mid<<endl;
55     }
56     return 0;
57 }
POJ 3273Monthly Expense (二分,最小值)

 

POJ 3273Monthly Expense (二分,最小值)

上一篇:POJ 3264 Balanced Lineup RMQ


下一篇:.Net Core 3 : 关于 WPF 中 System.Windows.Interactivity 的迁移问题