1

Suppose I have a given array A. Now there are multiple operations of the form

reverse i,j // means reverse the array Ai..j inclusive

and

print i,j

Print the array Ai..j.

Example ,

A = 6 9 1 10 4 15 9
reverse 2,3
A = 6 1 9 10 4 15 9
reverse 3,6
A = 6 1 15 4 10 9 9
print 1,4

6 1 15 4

I have heard that it can be done by cartesian trees. So I have been reading the blog here But I still can't understand how we can do this using cartesian tree, what is the key and value should be and how we should implement ?

Unbound
  • 233
  • 1
  • 11
  • `swap(i, j);` `i++` `j--` repeat until `i < j` – Haris Oct 11 '14 at 08:12
  • I was hoping someone who already know cartesian tree would be able to answer this question and for this there is no need for the site. I provided the site so that people can know which implementation of the cartesian tree am I following.(And there is no english site with cartesian tree implementation) – Unbound Oct 11 '14 at 08:19

1 Answers1

2

In this problem, a treap(aka Cartesian tree) with implicit key should be used(there is no key at all, it is just about merging them in right order). The value of a node is an array element that it represents. To implement reverse operation, you can maintain reverse flag for each node(true if it must be reversed, false otherwise) and push it lazily(to push here means to exchange left and right children of a node and flip the value of a flag in its children).

Pseudo code for push:

void push(Node node)
    if node.flag
        swap(node.left, node.right)
        if node.left != null
            node.left.flag = not node.left.flag
        if node.right != null
            node.right.flag = not node.right.flag
kraskevich
  • 17,514
  • 3
  • 26
  • 42
  • can you explain with an example please ?? I don't understand the part pushing ! – Unbound Oct 11 '14 at 08:31
  • if I swap the nodes,, wouldnt the key changed ? I mean left subtree should be less than node, but when you are swapping it becomes greater. – Unbound Oct 11 '14 at 09:53
  • @Unbound There is no key at all. There is nothing to change. – kraskevich Oct 11 '14 at 11:12
  • thanks , I was just having trouble to understand as to why , after merging the order would be the same as previous array. – Unbound Oct 16 '14 at 08:01