Number of columns in the segment - half the answer

Luo Gu original title
number p1182 column segments

The answer is just learning dichotomy of weak chicken

Not because the brush across the road to the shortest time Orgrimmar only to learn dichotomy

It is a very simple binary answer (nonsense

Binary answer, the nest is understood that the determination plus binary search, seeking the most generally applicable to the minimum or maximum value of the minimum or the like, to find answers section monotonic. The answer is in the range covered in binary search function with a judge to determine whether to meet the requirements of the answer, if happens to be the first to meet the requirements to find the answer.

Talk about this question, in fact, the beginning of the nest did not understand what search answers (section Shaa) actually Shoumo again is an easy example.

M is less than N is greater than 1, we divided up into N pieces of at least one section, at the two extremes, the former must be the maximum value of the N largest A_i positive integer, which is the maximum value of the N the total number of ($$ A_1 $$ + $ A_2 $ + ... + $ A_N $), then the answer must be in the [$ A_i $, ($ A_1 $ + $ A_2 $ + ... + $ A_N $ )] in this range!

Since determine the interval, and the rest is determined that

Lift your hands first Code

bool judge(int max){/*判断max是否能作为答案*/
   for(int i = 0; i < n; i++){/*还是"%ni"一遍,会发现其实tim记的就是如果要按max为答案分,能分成几组*/
       if(total+a[i]<=max) total += a[i];/*合起来比max小就是一组*/ 
       else total = a[i],tim++;/*合起来大了就把之前记下的那堆合成一组*/ 
   }
   return tim >= m;/*如果最后分的组多了的话,那么说明目前的max大了,少了就是小了*/ 
    
}

According to the return value is the max big returns 0, max small returns 1, then how to find and very clear

  while(lef<=rig){
        mid = (lef+rig)/2;
        total = 0, tim = 0;
        if(judge(mid)) lef = mid + 1;/*max小了就让中间值成为左端点,右半部分就是我们剩下要搜的区间*/ 
       else rig = mid - 1;/*max大了就让中间值成为右端点,左半部分就是我们剩下要搜的区间*/ 
    }

So the question, then the AC!

All codes

#include<bits/stdc++.h>
using namespace std;

int n,m,a[100100],lef,rig,mid,total,tim;

bool judge(int max){
   for(int i = 0; i < n; i++){
       if(total+a[i]<=max) total += a[i];
       else total = a[i],tim++;
   }
   return tim >= m; 
    
}

int main(){
    cin>>n>>m;
    for(int i = 0; i < n; i++){
        cin>>a[i];
        rig+=a[i];
        lef = lef > a[i] ? lef: a[i];
    }
    while(lef<=rig){
        mid = (lef+rig)/2;
        total = 0, tim = 0;
        if(judge(mid)) lef = mid + 1;
       else rig = mid - 1; 
    }
    cout<<lef;
    return 0;
}

Thank you!

Guess you like

Origin www.cnblogs.com/qmings/p/12099455.html