#include<bits/stdc++.h>
using namespace std;
#define int long long
#define PII pair<int,int>
const int M = 5e5 + 9;
int a[M];int n;
int tree[M];
bool cmp(PII a, PII b) {
if (a.first != b.first) {
return a.first < b.first;
}
else {
return a.second < b.second;
}
}
int ask(int x) {
int ans = 0;
for (;x;x -= x & -x)ans += tree[x];
return ans;
}
void update(int x, int y) {
for (;x <= n;x += x & -x)tree[x] += y;
}
signed main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
vector<PII>mv(M);
for (int i = 1;i <= n;i++) {
cin >> mv[i].first;
mv[i].second = i;
}
sort(mv.begin() + 1, mv.begin() + 1 + n, cmp);
for (int i = 1;i <= n;i++) {
a[mv[i].second] = i;
}
int sum = 0;
for (int i = 1;i <= n;i++) {
sum += ask(a[i]);
update(a[i], 1);
}
sum = n * (n - 1) / 2 - sum;
cout << sum << '\n';
return 0;
}
树状数组:逆序对
最新推荐文章于 2024-08-22 23:21:41 发布