<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

180. Inversions
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard



There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=i<j<=N and A[i]>A[j].

Input
The first line of the input contains the number N. The second line contains N numbers A1...AN.

Output
Write amount of such pairs.

Sample test(s)

Input
5
2 3 1 5 4

Output
3
Author:	Stanislav Angelyuk
Resource:	Saratov ST team Spring Contest #1
Date:	18.05.2003

<|response|>
1. Abridged Problem Statement  
Given an array A of N integers (1 ≤ N ≤ 65 537, 0 ≤ Ai ≤ 10^9), count how many index pairs (i, j) satisfy i < j and A[i] > A[j].

2. Key Observations  
- A brute-force double loop is O(N²), which is too slow for N up to ~65 000.  
- We need an O(N log N) method. Two classic approaches:  
  a) Merge-sort-based inversion counting.  
  b) Fenwick Tree (Binary Indexed Tree, BIT) with coordinate compression.  
- Fenwick Tree approach outline:  
  • Sweep the array from left to right.  
  • Maintain a data structure that counts how many previously seen elements exceed the current one.  
  • Since Ai can be as large as 10^9, first compress values into the range [1..N].

3. Full Solution Approach  
Step 1: Coordinate Compression  
- Copy all A[i] into a new list "vals."  
- Sort "vals" and remove duplicates.  
- Map each original A[i] to its 1-based rank in "vals." This rank lies in [1..M], where M ≤ N.

Step 2: Fenwick Tree (BIT)  
- Create a BIT of size M, initialized to zero.  
- BIT supports two operations in O(log M):  
  • add(pos): increment the count at index pos.  
  • query(pos): return the total count in [1..pos].

Step 3: Count Inversions  
- Initialize inversions = 0.  
- For i from 0 to N−1:  
   1. Let r = rank(A[i]).  
   2. Insert it first: add(r). Now i+1 elements have been seen.  
   3. query(r) = number of seen elements ≤ A[i] (including itself).  
   4. The remaining i+1 − query(r) seen elements are strictly greater and lie to the left, i.e. inversions ending at i. Add that to inversions.

Overall complexity: O(N log N) time, O(N) extra space.

4. C++ Implementation  
```cpp
#include <bits/stdc++.h>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

class Fenwick {
  public:
    int n;
    vector<int> tr;

    Fenwick(int _n = 0) { init(_n); }

    void init(int _n) {
        n = _n;
        tr.assign(n + 1, 0);
    }

    void add(int x) {
        for(; x <= n; x += (x & -x)) {
            tr[x]++;
        }
    }

    int query(int x) {
        int ret = 0;
        for(; x > 0; x -= (x & -x)) {
            ret += tr[x];
        }

        return ret;
    }
};

int n;
vector<int> a;

void read() {
    cin >> n;
    a.resize(n);
    cin >> a;
}

void solve() {
    // Count inversions with a Fenwick tree over compressed values. We sort and
    // dedupe the values, map each element to its 1-based rank, then sweep left
    // to right inserting ranks. After inserting the i-th element (i + 1 seen so
    // far), the number of already-inserted values that are <= a[i] is
    // query(a[i]); the rest, i + 1 - query(a[i]), are strictly greater values
    // sitting to its left, i.e. inversions ending at position i.

    vector<int> li = a;
    sort(li.begin(), li.end());
    li.erase(unique(li.begin(), li.end()), li.end());

    for(int i = 0; i < n; i++) {
        a[i] = lower_bound(li.begin(), li.end(), a[i]) - li.begin() + 1;
    }

    Fenwick fen(li.size() + 1);

    uint32_t answer = 0;
    for(int i = 0; i < n; i++) {
        fen.add(a[i]);
        answer += i + 1 - fen.query(a[i]);
    }

    cout << answer << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        // cout << "Case #" << test << ": ";
        solve();
    }

    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys

def main():
    data = sys.stdin.read().split()
    n = int(data[0])
    A = list(map(int, data[1:]))

    # 1. Coordinate compression
    vals = sorted(set(A))              # sorted unique values
    rank = {v: i+1 for i, v in enumerate(vals)}  # map value -> rank
    M = len(vals)

    # 2. Fenwick Tree implementation
    class Fenwick:
        def __init__(self, n):
            self.n = n
            self.fw = [0] * (n + 1)
        # point update: add v at index i
        def add(self, i, v=1):
            while i <= self.n:
                self.fw[i] += v
                i += i & -i
        # prefix sum [1..i]
        def sum(self, i):
            s = 0
            while i > 0:
                s += self.fw[i]
                i -= i & -i
            return s

    bit = Fenwick(M)
    inversions = 0

    # 3. Sweep through A
    for i, x in enumerate(A):
        r = rank[x]
        # how many seen elements <= x
        cnt_le = bit.sum(r)
        # seen so far = i, so seen > x = i - cnt_le
        inversions += (i - cnt_le)
        # mark this value
        bit.add(r, 1)

    # 4. Output result
    print(inversions)

if __name__ == "__main__":
    main()
```
