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?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
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?
Название |
---|
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 ?