Suppose you have two operations : 1 ADD L R x, add from L to R value x 2 SUM L R, get the sum from L to R.
How can you implement these using any typical BST like treap or splay tree?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Suppose you have two operations : 1 ADD L R x, add from L to R value x 2 SUM L R, get the sum from L to R.
How can you implement these using any typical BST like treap or splay tree?
Name |
---|
why do you want to use exactly BST ? there are better data structures, segment tree will work as well
BST's are mostly used to store a sorted collection of values and be able to efficiently answer queries of the form "What is the element at index 'k'?" or "How many elements bigger/smaller than 'n' are there?", etc.. If you're gonna use range queries, segment trees or BIT's are the way to go. Much easier to code too, btw.
Seems that your question is similar to this problem SPOJ HORRIBLE
I am not so sure about BST, but with BIT and Segment Trees should be easier to implement.
The following code shows a BIT implementation topcoder forum.
Cause, i know segment tree and bit, i want to do it with bst.
http://www.codeforces.com/contest/284/submission/3345224
see this for example, i can't understand how he does it, but he uses treap to compute the sum from 1 to k.
here is my code for the problem problem
I used segment tree. code link : code
hope it helps :).
Consider a BST with the following satellite data in its nodes:
And also a function getSum(int l, int r, int a, int b, node *t) that returns the sum of all elements from indexes l to r ([a,b] is the range of indexes in the sub-tree rooted at the current node t). You'd call getSum(l, r, 0, size_of_tree, root), and the code for the function would be something like this...
Awesome! Thank you very much.
You can also implement SPLIT and MERGE in the BST. You then split the tree twice to isolate the nodes in the range [l, r]. Keep in mind SPLIT takes log n time (assuming the tree is balanced). Then you just read the aggregate statistic (sum in this case) from the root of this new tree. Then you can merge them together in the end.
How to get range sum with MST ?