持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情
数列分段 Section II
题目描述
对于给定的一个长度为N的正整数数列 ,现要将其分成 ()段,并要求每段连续,且每段和的最大值最小。
关于最大值最小:
例如一数列 要分成 段。
将其如下分段:
第一段和为 ,第 段和为 ,第 段和为 ,和最大值为 。
将其如下分段:
第一段和为 ,第 段和为 ,第 段和为 ,和最大值为 。
并且无论如何分段,最大值不会小于 。
所以可以得到要将数列 要分成 段,每段和的最大值最小为 。
输入格式
第 行包含两个正整数 。
第 行包含 个空格隔开的非负整数 ,含义如题目所述。
输出格式
一个正整数,即每段和最大值最小为多少。
样例 #1
样例输入 #1
5 3
4 2 4 5 1
样例输出 #1
6
提示
对于 的数据,。
对于 的数据,。
对于 的数据,,,, 答案不超过 。
分析
这题要得到每段和的最大值最小,分成段,很显然,暴力的话妥妥,于是我们要考虑更好的优化,我们可以通过二分一下最小的最大值,然后再在函数中实现,从第一个数往后遍历,用记录,如果这个值了,就记录分了一段,最后返回分了几段,如果段,说明答案在包含的左边,否在再不包含它的右边。最后输出答案!
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <iomanip>
#define ll long long
#define AC return
#define Please 0
using namespace std;
const int N=100010;
const double eps=1e-9;
typedef pair<int,int>PII;
typedef unsigned long long ull;
int n,m,k,a[N],b[N];
inline int read(){//快读
int x=0,f=1;char ch=getchar();
while(ch<'0' || ch>'9'){
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9'){
x=x*10+ch-'0';
ch=getchar();
}
AC x*f;
}
bool check(int x){
ll sum=0;
int cnt=1;
for(int i=1;i<=n;i++){
if(a[i]>x){
return 0;
}
if(sum+a[i]<=x){
sum+=a[i];
}
else{
cnt++;
sum=a[i];
}
}
return cnt<=m;
}
int main(){
n=read(),m=read();
for(int i=1;i<=n;i++){
a[i]=read();
}
int l=0,r=2e9;
while(l<r){
int mid=l+r>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
cout<<l<<endl;
AC Please;
}
希望能帮助到大家()!