Bipartite Title - line 2

Sequence 2

Positive integer a for a given length of N (N≤100000) column AI, want now divided into M (M≤N) segments and each successive requirements, and the maximum and minimum of each segment.

About the smallest maximum value: for example, a number of columns 42451 to be divided into 3 sections. Segment which is as follows: [42] [45] [1]
paragraphs 1 and 6, paragraphs 2 and 9, 1, and a maximum of paragraphs 3 and 9.

Segment which is as follows: [4] [24] [51] paragraphs 1 and 4, paragraphs 2 and 6, 6, and for the maximum value of paragraph 3 and 6. And in any case the segment, the maximum value of not less than 6.

To get the number of columns can be 42,451 to be divided into three segments, and a minimum of 6 maximum.

Input formats:

Line 1 comprises two positive integers N, M. The second row separated by a space comprising N non-negative integers ai, meaning as the subject. All data ai guaranteed in all integers.

Output formats:

A positive integer, that is how much each segment and maximum minimum.

Sample input:

5 3 4 2 4 5 1

Sample output:

6

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define M 100010
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int n,m;//长度为n,需要分成m段
ll a[M];
ll sum,mmax;
bool check(ll num){    //检查是否能在最大和为num情况下,分成m段
    ll t = 0;
    int cnt = 1;
    for(int i=0; i<n; i++){
        t += a[i];
        if(t > num){
            cnt++;
            t = a[i];
        }
    }
    return cnt<=m;
}
int main(){
    cin >> n >> m;
    ll l=0,r=0;    //进行二分的左端点,右端点
    for(int i=0; i<n; i++){
        scanf("%lld",&a[i]);
        r += a[i];    //所有数据之和
        l = max(l,a[i]);  //找到数据里最大的那个
    }
    ll mid;   //把mmax到——sum视作连续数,对其进行二分
    while(l<=r){
        mid = (l+r)/2;
        if(check(mid))  //如果当前mid可以:那么尝试更小的数
            r = mid - 1;
        else
            l = mid + 1;  //mid不可以
    }
    cout << l << endl;
    return 0;
}

Note: long long

Published 62 original articles · won praise 0 · Views 1744

Guess you like

Origin blog.csdn.net/jhckii/article/details/104455882