[Ybtoj high-efficiency advanced 1.3] [two points] sequence segmentation

[Ybtoj high-efficiency advanced 1.3] [two points] sequence segmentation

topic

Insert picture description here


Problem-solving ideas

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


Code

#include<iostream>
#include<cstdio>
using namespace std;
int a[100020],n,m,l,r;
bool pd(int x)
{
    
    
	 int sum=0,ans=1;  //sum是当前段的和,ans是当前分了几段
	 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()
{
    
    
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n;i++)
	{
    
     
	    scanf("%d",&a[i]);
	    r+=a[i];
	}
	l=1;
	while (l<r)
	{
    
    
		  int mid=(l+r)/2;
		  if (pd(mid))
		     r=mid;
		     else l=mid+1;
	}
	printf("%d",l);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45621109/article/details/111994810