二分贪心专题F

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
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
合并一些数字为若干组 是的各组和的最大值最小

依然是二分答案

上限为数字的总和,下限为最大的数字

bool test(int x)
{
	int s,num,i;  
    s=0;  
    num=1;  
    for(i=0;i<n;i++)  
    {  
        if(s+a[i]<=x) s+=a[i];  
        else  
        {  
            s=a[i];  
            num++;  
        }  
    }  
    if(num>m)return 0;  
    else return 1; 
}

不断加和直至当前总和大于答案

源代码:

#include<iostream>
using namespace std;
int m,n;
int a[100016];
bool test(int x)
{
	int s,num,i;  
    s=0;  
    num=1;  
    for(i=0;i<n;i++)  
    {  
        if(s+a[i]<=x) s+=a[i];  
        else  
        {  
            s=a[i];  
            num++;  
        }  
    }  
    if(num>m)return 0;  
    else return 1; 
}

int main()
{
	cin>>n>>m;
	int tot=0,max=0;
	for (int i=1;i<=n;i++) 
	{
		cin>>a[i];
		tot+=a[i];
		if (a[i]>max) max=a[i];
	}
	int left=max;int right=tot;int mid;
	mid=(left+right)/2;
	while (left<right)
	{	
		if (test(mid)) right=mid-1;
		else left=mid+1;
		mid=(left+right)/2;
	}
	cout<<mid;
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/ruozhalqy/article/details/54781441