Sequence segments II

Topic Link

 

The meaning of problems

Is divided into a sequence of M successive segments, and so where the minimum and maximum period.

 

Thinking

The obvious answer monotone larger answer, the number of sub-segments of relatively less.

Can be half a value, then see if you can answer this value as a sub-paragraphs, if the number of segments than M, explain the answer should be larger than this value, whereas even smaller.

(Dichotomous answer introductory questions ah). . .

 

Good idea to write a dichotomous answer template. . Li Yudong great God-half of the template can not read. . .

Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<queue>
using namespace std;

const int mx = 1e5 + 5;
const int inf = 1e9;

int n, m;
int a[mx];

inline bool check(int mid){
    int sum = 0, cnt = 0;
    for(int i = 1; i <= n; i++){
        if(sum+a[i] > mid){
            sum = a[i]; cnt++; continue;
        }
        sum += a[i];
    }
    return cnt >= m;
}

int main(){
    cin >> n >> m;
    int l = 0, r = 0;
    for(int i = 1; i <= n; i++) scanf("%d", &a[i]), l = max(l, a[i]), r += a[i];
    
    while(l <= r){
        int mid = (l+r)>>1;
        if(check(mid)) {
            l = mid+1;
        }
        else r = mid-1;
    }
    
    printf("%d\n", l);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Maktub-blog/p/10994936.html