If the given array's size is N then what should I declare the size of the array for Segment Tree?
If I set the Segment Tree's array size to 2 × 2k (or maybe something like this 2 × 2k + 5) where k = ⌈ log2N⌉, won't that be enough? If not, then why?
# | 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 |
If the given array's size is N then what should I declare the size of the array for Segment Tree?
If I set the Segment Tree's array size to 2 × 2k (or maybe something like this 2 × 2k + 5) where k = ⌈ log2N⌉, won't that be enough? If not, then why?
Name |
---|
2*N is enough.
No, 2 * N will not hold for any N that is not a power of 2.
For example if N = 105 then you will need roughly 262143 sized segment tree, which is greater than 2 * N. Actually 4 * N is the safest way.
2*N is sufficient size for a segment array(irrespective of whether N is a power of 2 or not).Here's an article about the approach to do it: http://codeforces.net/blog/entry/18051
Actually if you can write N as 2x where x is an integer then you can see that you need 2x + 1 - 1 nodes in your segment tree. So what can you do for other N's? Well, you can find the next power of 2 after N, let's say it is 2x and then you can declare 2x + 1 - 1 sized segment tree. So yes it will work as you said.
But if you don't want to do that much calculation, you can always declare 4 * N with your eyes closed!
Here is a nice Quora answer which proves that 4 is in fact the smallest k such that kN is enough space for a segment tree on an array of size N.
But iterative segment tree takes only 2N space.
See more here.
Sure, the page I linked to assumes the recursive implementation, so the result it proves is not valid for the iterative implementation you suggest.
I usually adopt the implementation of segment tree mentioned in this book Competitive Programmer's Handbook — a new book on competitive programming.
According to my own understanding, if there are N elements, then I will find the minimum M = 2m that is no less than N. Then, the total number of nodes in the segment tree should be 2 * M.
You should change a little bit k=(int)log2(N)+1; Rest of them are ok .