[Ybtoj Chapter 3 Example 1] Number sequence segmentation [Two points]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem solving ideas

The title description appears similar to the meaning of "maximum minimum", which is one of the most typical features of monotonic answers.

Suppose the optimal solution is S. Because of the optimality of S, if the sum of each segment is required to be less than s, it must not be divided into continuous M segments, but more continuous segments. If the sum of each segment can be >s, then there must be a division scheme so that the total number of segments does not exceed M.

Therefore, the answer lies at the demarcation point of segmentation feasibility.


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int n,m,a[100010],l,r,mid,maxn=0,k;
bool check(int x){
    
    
	long long cnt=1,s=0;
	for(int i=1;i<=n;i++)
	{
    
    
		if(s+a[i]>x)
		{
    
    
			cnt++;
			s=a[i];
		}
		else s+=a[i];
	}
	if(cnt>m)
		return 0;
	else return 1; 
}
int main(){
    
    
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
    
    
		scanf("%lld",&a[i]);
		maxn+=a[i];
		k=max(k,a[i]);
	}
	l=k,r=maxn+1;
	while(l<r)
	{
    
    
		mid=(l+r)>>1;
		if(check(mid))
			r=mid;
		else l=mid+1;
	}
	printf("%d",l); 
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111749708