_kryptonyte_'s blog

By _kryptonyte_, history, 9 years ago, In English

Problem Link : http://poj.org/problem?id=3277 The full code, http://ideone.com/RF1JfE

This is a very straight forward segment tree problem( if I don't miss anything ) , but unfortunately it just don't get AC. Obviously I miss something. Can anybody help. I try to build a seg tree with minimum 2 range sized leaf nodes by following code where Tree[nd] holds the height of the range.

void build( int nd , int st , int en ) {
    Tree[nd] = 0 ;
    if( st+1 == en )return ;
    build( (nd<<1) , st , (st+en)>>1 );
    build( (nd<<1)+1 , (st+en)>>1 , en );
} 

Then I update like following manner, here l,r is the index of the value given in the problem,

void update( int nd , int st , int en ) {
    propagate(nd,st,en) ;
    if( st == en ) return  ;
    if( st > r || en < l ) return ;
    if( st>=l && en <= r ) {
        Tree[nd] = max( Tree[nd] , h ) ;
        return ;
    }
    if( st+1 == en ) return  ;
    update( (nd<<1) , st , (st+en)>>1 );
    update( (nd<<1)+1 , (st+en)>>1 , en );
}

And finally run the query,

long long query( int nd , int st , int en ) {
    propagate(nd,st,en) ;
    if( st == en ) return 0 ;
    if( en-st == 1 ) {
        long long ans = (V[en]-V[st])*Tree[nd] ;
        return ans ;
    }

    return query( (nd<<1) , st , (st+en)>>1 )
           +query( (nd<<1)+1 , (st+en)>>1 , en );
}
  • Vote: I like it
  • +8
  • Vote: I do not like it

»
9 years ago, # |
Rev. 2   Vote: I like it +11 Vote: I do not like it

For this problem, I'd recommend doing a scanline from left to right, keeping track of the highest visible height at each coordinate and multiplying accordingly.

Here's the code for easier understanding...

Pretty C++11 Code: Here

Horrible old C++ code (necessary for POJ): Here

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    Thanks, But after a lot of debugging I finally ACed it with segment tree. And also your solution is elegant. Got new idea from your approach.