[Ybtoj Advanced Higher Education 1.3] A. Number sequence segmentation [two points]

Insert picture description here

analysis

Divide the maximum value of all the segments and
accumulate the sum of all numbers as the initial right boundary

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

int n,m,a[100001],l,r,mid;

int jq(int x)
{
    
    
	int sum=0,ans=1;
	for(int i=1;i<=n;i++)
	{
    
    
		if(a[i]>x) return 0;
		if(sum+a[i]>x)
		{
    
    
			sum=a[i];
			ans++;
		}
		else sum+=a[i];
	}
	if(ans<=m) return 1;
	else return 0;
}

int main()
{
    
    
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i];
		r+=a[i];
	}
	l=1;
	while(l<r)
	{
    
    
		int mid=(l+r)>>1;
		if(jq(mid)) r=mid;
		else l=mid+1;
	}
	cout<<l;
	return 0;
}

Guess you like

Origin blog.csdn.net/dglyr/article/details/112384358