Topic Connection
https://leetcode.com/problems/count-of-smaller-numbers-after-self/
Count of Smaller Numbers after selfdescription
You were given an integer array nums and you had to return a new counts array. The counts array has the property where $counts [i]$ are the number of smaller elements to the right of $nums [i]$.
Example:
Given $nums = [5,2,6,1]$
The right of 5 there is 2 smaller elements (2 and 1).
The right of 2 there are only 1 smaller element (1).
The right of 6 there is 1 smaller element (1).
The right of 1 there is 0 smaller element.
Return the array $[2, 1, 1, 0]$.
Line tree to find the number of reverse, first discretization, and then using line tree statistics.
Class Solution {Private:typedef vector<int> Vec;public:vec countsmaller (vec& nums) {VEC ans;int n = 0;if (!) ( n = nums.size ())) return Ans;ans.resize (n, 0), ret = new P[n + 10];for (int i = 1; I <= n; i++) Ret[i] = P (nums[i-1), i); sort (ret + 1, ret + n + 1), SEG = new int[(n + +) << 2];memset (seg, 0, sizeof (int) * ((n + 2) <<)); for (i NT i = 1; I <= N; i++) {int v = query (1, 1, N, Ret[i].id, N), insert (1, 1, N, ret[i].id); ans[ret[i].id-1] = v;} delete[]seg; Delete[]ret;return ans;} private:struct P {int V, id; P (int _i_ = 0, int _j_ = 0): V (_i_), id (_j_) {}friend bool operator< (const p &a, const p &b) {return A.V = B.V ? a.ID < B.ID:A.V < B.V;}} *ret;int *seg;inline void Insert (int root, int l, int r, int p) {if (P > R | | p < l) return;if (P <= L && P >= r) {seg[root]++; return;} int mid = (L + R) >> 1;insert (Root << 1, L, Mid, p); Insert (Root << 1 | 1, mid + 1, r, p); Seg[root] = seg [Root << 1] + SEg[root << 1 | 1];} inline int query (int root, int l, int r, int x, int y) {if (x > R | | y < L) return 0;if (x <= l && y > = r) return seg[root];int ret = 0;int mid = (L + R) >> 1;ret + = query (Root<<1, L, Mid, X, y); ret + = query (root << 1 | 1, Mid + 1, r, X, y); return ret;}};
Leetcode Count of Smaller Numbers after self