I'm not sure what the segment tree algorithm looks like.
This can be done in O ((n + q) log n) time using decorated trees. Each node decoration consists of counting descendants and bits, which upon installation implicitly flips the entire subtree. To query, use child counting to jump to the corresponding node. To cancel from u to v , splay u to the root, separate its left subtree uL , splay v to the root, disconnect its right subtree vR , invert flip bits on all uL , v , vR , attach uL to the field from which vR came , splay u , reconnect vR .
Key: ? denotes an anonymous node ^ denotes a subtree u / \ uL ? ^ / \ v ? ^ ^ uL v ^ / \ u vR \ ^ ? ^ vR v
source share