1

Hi i am learning segment tree. Buildilding the segment tree using the recursive methodis clear to me , i have implemented it like this:

void build( int n, int b, int e){
    if(b > e) return;
    else if (b == e) { tree[n] = arr[b]; return }
    build(n*2 , b , (b+e)/2 );
    build(n*2+1 , (b+e)/2+1 , e );
    tree[n] =  tree[n*2] + tree[n*2 + 1] ;
}

but i have seen a shoter implementation like this :

    void build() {  // build the tree
      for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1];
   }

i understand that t[i<<1] is same as  t[2*i] and t[i<<1|1] is same as t[2*i+1]

but how does that logic help i building the segment tree?? a simple example would be very helpful

kshitij singh
  • 363
  • 2
  • 10
  • 19
  • can you show the complete original code of "short implementation"? I think build() function only builds the other node except the leave, so the leave has initated – malioboro Feb 22 '16 at 17:07
  • @malioboro here is the link : https://ideone.com/0K8XPI and here is the explanation that i was looking up: http://codeforces.com/blog/entry/18051 – kshitij singh Feb 23 '16 at 03:27

1 Answers1

0

Actually there is a different "function" of build() in your code and their code. In your code, when you build the segment tree you also input the leaves value, but in their code, they input the leaves value in this statement:

for (int i = 0; i < n; ++i) scanf("%d", t + n + i);

and use build() to only fill the other node

malioboro
  • 3,097
  • 4
  • 35
  • 55