Number sequence segmentation (two points)

Sequence segmentation

Insert picture description here

Problem solving ideas

Suppose the optimal solution is mid . If the sum of each segment is less than mid,
there must be an optimal solution
. The number of segments does not exceed m,

otherwise mid is increased

AC code

#include<cstdio>
#include<algorithm> 
using namespace std;
int n,m,l,r,a[100005];
bool check(int x)//判断
{
    
    
	int sum=0,num=1;//sum为当前段的和,num为分了多少段
	for(int i=1;i<=n;i++)
	 if(sum+a[i]>x)
	 {
    
    
	 	num++;
		sum=a[i];
		if(a[i]>x)return 0;//记得特判,如果当前点已经大于,就无法分段
	 }
	 else sum+=a[i];
	return num>m; 
}
int main()
{
    
    
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
    
    
		scanf("%d",&a[i]);
		l=max(l,a[i]); //找最大值
		r+=a[i];//和
	}
	while(l<r)//二分
	{
    
    
		int mid=(l+r)/2;
		if(check(mid))l=mid+1;
		else r=mid;
	}
	printf("%d",l); 
	return 0;
}

Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/112132661