码迷,mamicode.com
首页 > 其他好文 > 详细

luogu p1182 数列分段Section II

时间:2017-12-03 13:02:58      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:文件   names   space   最大和   false   span   name   divide   如何   

题目描述

对于给定的一个长度为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。

题解

一道二分题。
我们可以用mid进行二分,如果符合条件就把它输出。
用check函数判断最大和为l时的整体情况,
返回true就是l太小,返回false就是r太大。

【CODE】

#include<iostream>
using namespace std;
int n,m;
int a[100001];
int i;
bool check(int x)
{
    int ans=1;
    int tot=0;
    for(i=1;i<=n;i++)
    {
        if(tot+a[i]<=x)tot+=a[i];
        else 
        {
            ans++;
            tot=a[i];
        }
    }
        if(ans>m)return true;
        else return false;
}
int main()
{
    cin>>n>>m;
    for(i=1;i<=n;i++)
    cin>>a[i];
    int r=0,l=0;
    for(i=1;i<=n;i++)
    {
        r+=a[i];
        l=max(l,a[i]);
    }
    while(l<r)
    {
        int mid=(l+r)/2;
        if(check(mid))l=mid+1;
        else r=mid;
    }
    cout<<l<<endl;
    return 0;
}

贴出一组样例的数据希望能帮助理解。

l=5  r=16
mid=21
tot=4 ans=1
tot=6 ans=1
tot=10 ans=1
tot=5 ans=2
tot=6 ans=2
l=5  r=10
mid=10
tot=4 ans=1
tot=6 ans=1
tot=4 ans=2
tot=5 ans=3
tot=6 ans=3
l=5  r=7
mid=7
tot=4 ans=1
tot=6 ans=1
tot=4 ans=2
tot=5 ans=3
tot=6 ans=3
l=5  r=6
mid=6
tot=4 ans=1
tot=2 ans=2
tot=4 ans=3
tot=5 ans=4
tot=1 ans=5
l=6  r=6
mid=5

luogu p1182 数列分段Section II

标签:文件   names   space   最大和   false   span   name   divide   如何   

原文地址:http://www.cnblogs.com/deinen/p/7965737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!