Algorithm 1(Fenwick Tree):
Time Complexity = $O(n \log n)$ .
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
using PII = pair<int, int>;
class FenwickTree {
private:
vector<int> nodes; // Nodes that store the tree array
public:
// Constructor: Initializes the segment tree with a given array length
FenwickTree(int n) {
nodes.resize(n + 1, 0);
}
// Single point update : increase the value of position u by val
void update(int u, int val) {
while (u < nodes.size()) {
nodes[u] += val;
u += u & -u;
}
}
// Interval query : Return the prefix sum from position 1 to u.
int query(int u) {
int res = 0;
while (u) {
res += nodes[u];
u -= u & -u;
}
return res;
}
long long numOfReverseOrderPairs(vector<PII>& nums) {
// Arrange nums in descending order
sort(nums.begin(), nums.end(), greater<PII>());
// Count the number of larger numbers on the left side of each number
long long ans = 0;
for (auto [val, index] : nums) {
index++;
ans += query(index);
update(index, 1);
}
return ans;
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
// <value, index>
vector<PII> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i].first;
nums[i].second = i;
}
FenwickTree T(n);
cout << T.numOfReverseOrderPairs(nums) << '\n';
return 0;
}
Algorithm 2(Merge Sort):
Time Complexity = $O(n \log n)$ .
#include <iostream>
using namespace std;
const int N = 1e5;
long long cnt;
void mergeAndCount(int arr[], int low, int mid, int high) {
int temp[N];
for (int i = low; i <= high; ++i) {
temp[i] = arr[i];
}
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high) {
if (temp[i] <= temp[j]) {
arr[k++] = temp[i++];
}
else {
arr[k++] = temp[j++];
cnt += mid - i + 1;
}
}
while (i <= mid) {
arr[k++] = temp[i++];
}
while (j <= high) {
arr[k++] = temp[j++];
}
}
void mergeSortAndCount(int arr[], int low, int high) {
if (low >= high) {
return;
}
int mid = (low + high) / 2;
mergeSortAndCount(arr, low, mid);
mergeSortAndCount(arr, mid + 1, high);
mergeAndCount(arr, low, mid, high);
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int arr[N], n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
mergeSortAndCount(arr, 0, n - 1);
cout << cnt;
return 0;
}