Friday, August 07, 2009


Well I fixed my algorithm and managed to solve the problem (see previous post). Here is a general overview.

  1. Create array of cumulative sums
  2. Create Segment tree
  3. Answer queries using segment tree
Each node of the segment tree contained about the location of the max and min elements of the cumulative sum array, that was spanned by the interval. For instance, the node that pertained to the interval [2,4] would contain information about the max and min elements of Sum[2...4], where Sum[] is the cumulative sum array. Also other information might need to be stored in each node, but I'll leave that up to you to discover. Don't want to spoil all the fun now do I?

Now I'm moving onto GSS3, which is more or less the same problem but with the ability to update sequence elements in addition to making queries. At the moment I plan to use the same code but modify certain parts so they they use binary indexed trees.

Found this to be a pretty interesting problem. Think I might try to implement a version for working with 2D arrays. Really it's not too hard to extend to more dimensions but the code just gets longer though the thought process stays the same. To me this is probably the major advantage of using segment trees over sparse arrays. But I must admit that I am not all that comfortable with the sparse array method, so it might extend just as easily (though I don't see it).


Raven said...

Interesting. I think I used a binary indexed tree also (for both 1 and 3), though I'm not 100% sure as TC tutorials tend to confuse more than enlighten.

Nick said...

I tried using a Binary Indexed Tree for 3 but it was too slow. Maybe there is some trick with that method that I'm just not seeing.