1. 程式人生 > >二分貪心專題F

二分貪心專題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;
}