Problem 110
Count Smaller Numbers After Self
Hard · 30 pts · Array, Divide and Conquer, Binary Indexed Tree
Problem
You are given an array of N integers. For every position i, count how many elements to the right of position i are strictly smaller than A[i]. Print the N counts in order. The simple O(N²) double loop is too slow for N = 100,000. Process the array from right to left and keep a Fenwick tree (binary indexed tree) over the values seen so far: for each element, query how many smaller values have been inserted, then insert it. A modified merge sort also works.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print N counts, space-separated.
Constraints
1 <= N <= 100000; -10000 <= A[i] <= 10000
Example input
4 5 2 6 1
Example output
2 1 1 0
Explanation
For 5 2 6 1: to the right of 5 are 2, 6 and 1, and two of them (2 and 1) are smaller. To the right of 2, only 1 is smaller. To the right of 6, only 1 is smaller. Nothing is right of 1. So the answer is 2 1 1 0.