Inversions en
Inversions en
• Given a sequence of integers a1, a2,…, an. A pair (I, j) is called an inversion if i < j and ai > aj
• Compute the number Q of inversions
• Input
• Line 1: contains a positive integer n ( 1 <= n <= 106 )
• Line 2: contains a1, a2,…, an ( 0 <= ai <= 106 )
• Output
• Write the value Q module 109 + 7
• Example
Inversion: Hint
L i M M+ j R
1
2 3 8 10 15 20 25 4 5 14 19 21 29
Implementation
#include <bits/stdc++.h>
#define N 1000006
using namespace std;
int const MOD = 1e9+7;
int n, a[N];
int ta[N];
Implementation
int countMerge(int left, int mid, int right){
int i = left, j = mid + 1, k = left, inv_count = 0;
while ((i <= mid) && (j <= right)) {
if (a[i] <= a[j]) ta[k++] = a[i++];
else {
ta[k++] = a[j++];
inv_count = (inv_count + (mid - i + 1)) % MOD;
}
}
while (i <= mid) ta[k++] = a[i++];
while (j <= right) ta[k++] = a[j++];
for (i = left; i <= right; i++) a[i] = ta[i];
return inv_count;
}
Implementation
int countInversion(int left, int right){
int mid, inv_count = 0;
if (right > left) {
// Divide the array into two parts and call mergeSort() for each of the parts
mid = (right + left) / 2;
// Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging
inv_count = (inv_count + countInversion(left, mid)) % MOD;
inv_count = (inv_count + countInversion(mid + 1, right)) % MOD;
inv_count = (inv_count + countMerge(left, mid, right))% MOD;
}
return inv_count;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
cin >> n;
for (int i=1; i<=n; i++) cin >> a[i];
cout << countInversion(1, n);
return 0;
}