inversion

 avatar
user_8384735
c_cpp
2 years ago
750 B
6
Indexable
Never
#include<iostream>
using namespace std;

typedef long long int ll;
const int MAX = 500010;

int q[MAX], n;


ll merge(int l, int r){
    if (l >= r) return 0;
    ll res;
    int mid = (l + r) >> 1;
    res = merge(l, mid) + merge(mid+1, r);
    
    int i = l, j = mid + 1, k = 0;
    int tmp[MAX];
    while (i <= mid && j <= r){
        if (q[i] <= q[j]) tmp[k++] = q[i++];
        else res += (mid - i) + 1, tmp[k++] = q[j++];
    }
    while (i <= mid) tmp[k++] = q[i++];
    while (j <= r) tmp[k++] = q[j++];
    for (int i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
    return res;
}
int main(){
    while (cin >> n && n){
        for (int i = 0; i < n; i++)
            cin >> q[i];
        cout << merge(0, n - 1) << endl;    
    }
    
}