You are given an array of n integers. Using segment tree how can you find for each number how many numbers are smaller than this are exist before that number. For example:
input: (first number is the value of n) 5 1 4 2 5 3
output: 0 1 1 3 2
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | Kevin114514 | 3611 |
| 4 | jiangly | 3583 |
| 5 | strapple | 3515 |
| 6 | tourist | 3470 |
| 7 | dXqwq | 3436 |
| 8 | Radewoosh | 3415 |
| 9 | Otomachi_Una | 3413 |
| 10 | Um_nik | 3376 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 164 |
| 2 | adamant | 150 |
| 3 | Um_nik | 146 |
| 4 | Dominater069 | 144 |
| 5 | errorgorn | 141 |
| 6 | cry | 139 |
| 7 | Proof_by_QED | 136 |
| 8 | YuukiS | 135 |
| 9 | chromate00 | 134 |
| 9 | TheScrasse | 134 |
You are given an array of n integers. Using segment tree how can you find for each number how many numbers are smaller than this are exist before that number. For example:
input: (first number is the value of n) 5 1 4 2 5 3
output: 0 1 1 3 2
| Name |
|---|



Good day to you,
WLOG — we will assume that all numbers are lesser/equal N (as long as this isn't true, we can "normalize" the numbers {with usage of sort or map to fulfill this}).
Now iterate through array from left to right, while having Segment Tree (or easier Fenwick) which can:
Add +1 to sigle element (interval not necessary)
Sum on interval
You firstly use "Sum on interval [0,A[i]-1]"
Secondly "Add +1 to element A[i]"
Why does it work? As you can see — after each element, all elements from its prefix have +1 added on position of its values, so if you query on interval [0,A[i]-1] you will get the sum of all elements with value 0,1,2,...,A[i]-2,A[i]-1
Hope it was at least slightly understandable.
Good Luck & Have Nice Day!
Thanks
Let the array be A. Let 1 <= A[i] <= 10^5. If the numbers can be larger, map them.
Suppose update(i, x) replaces value of i-th leaf node with x in segment tree. query(i, j) returns sums of all elements within [i, j] range.
Now, iterate the array from left to right. Let's work with first element first.
You want to know how many numbers so far are smaller than A[1]. So you just find query(1, A[1] — 1) from segment tree which is 0. Now,A[1] might be smaller than the next numbers. So, do update(A[1], 1).
Now, next number is A[2]. You have inserted all numbers before that in seg tree. You want to know how many of them are smaller than A[2]. You just do query(1, A[2]-1) which will result in 1.
So, the algorithm is like:
How to make query and update functions? That's actually the very basoc stuff segment tree do, you should study more about seg tree first if you get stuck there.
Now I have coded it. And it works! Thanks!