Binary Search Tree
Time limit2sMemory limit256 MB
Given n BSTs, insert a value w into every tree in a range [l, r], or report the sum of node values visited when searching for a in tree x.
- Level
Hard8 of 10
- Topics
- Segment tree, Tree, Binary search
- Solved
- No attempts yet
Problem
A binary search tree (BST) is a basic data structure. It is a rooted binary tree that stores a value in each node. If node contains value , all values in the left subtree of are less than , and all values in the right subtree of are greater than . To keep the details uniform, here is an implementation of finding a value in a BST rooted at node :
Here, is the left child of , is the right child of , and is the value of . If has no left child (or right child), () is . Let be the array of all nodes visited by find(root, a). The cost of find(root, a) is the sum of over all . There are empty BSTs and operations, and you must process them quickly. There are two kinds of operations. Operation 1 is written as 1 l r w: for each , insert the integer into the -th BST. It is guaranteed that is not already present in these BSTs. Insertion starts at the root and follows the same path as find, but instead of the final find(0, w) call, it creates a new node with value at that position and returns. Operation 2 is written as 2 x a: calculate the cost of finding in the -th BST.
Input
The first line contains two integers and (), the number of BSTs and the number of operations. Then lines follow, each describing one operation in the form 1 l r w (; ) or 2 x a (; ). It is guaranteed that all inserted numbers are different from each other.
Output
For each operation of the second kind, output one line containing the cost as a single integer.