P1182 数列分段Section II

题目描述

对于给定的一个长度为N的正整数数列A[i],现要将其分成M(M≤N)段,并要求每段连续,且每段和的最大值最小。

关于最大值最小:

例如一数列4 2 4 5 1要分成3段

将其如下分段:

[4 2][4 5][1]

第一段和为6,第2段和为9,第3段和为1,和最大值为9。

将其如下分段:

[4][2 4][5 1]

第一段和为4,第2段和为6,第3段和为6,和最大值为6。

并且无论如何分段,最大值不会小于6。

所以可以得到要将数列4 2 4 5 1要分成3段,每段和的最大值最小为6。

输入输出格式

输入格式:

 

输入文件divide_b.in的第1行包含两个正整数N,M,第2行包含N个空格隔开的非负整数A[i],含义如题目所述。

 

输出格式:

 

输出文件divide_b.out仅包含一个正整数,即每段和最大值最小为多少。

 

输入输出样例

输入样例#1:
5 3
4 2 4 5 1
输出样例#1:
6

说明

对于20%的数据,有N≤10;

对于40%的数据,有N≤1000;

对于100%的数据,有N≤100000,M≤N, A[i]之和不超过10^9。

二分答案,贪心划分区间。

 1 /*by SilverN*/
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 using namespace std;
 8 const int mxn=100010;
 9 int read(){
10     int x=0,f=1;char ch=getchar();
11     while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
12     while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
13     return x*f;
14 }
15 int n,m;
16 int a[mxn];
17 int solve(int limit){
18     int res=1;
19     int smm=0;
20     for(int i=1;i<=n;i++){
21         if(a[i]>limit)return n;//单个数大于区间限制,直接返回极大值
22         if(smm+a[i]<=limit){
23             smm+=a[i];
24             continue;
25         }
26         res++;
27         smm=a[i];
28     }
29     return res;
30 }
31 int main(){
32     n=read();m=read();
33     int i,j;
34     int mx=0;
35     for(i=1;i<=n;i++) a[i]=read();
36     int l=1,r=1e9;
37     int ans;
38     while(l<=r){
39         int mid=(l+r)>>1;
40         int tmp=solve(mid);
41 //        printf("test: %d %d
",mid,tmp);
42         if(tmp>m)l=mid+1;
43         else r=mid-1,ans=mid;
44     }
45     printf("%d
",ans);
46     return 0;
47 }
48 /*
49 10 2
50 1 9 7 4 10 8 2 8 3 9
51 */
原文地址:https://www.cnblogs.com/SilverNebula/p/5885485.html