题目链接:逆序数
解题思路:逆序数模板题,将数值离散化后把求值的逆序数转化成求其rank的逆序数。利用树状数组提升标记数组的效率。注意i - get_sum(rnk[i])表示在长度为i,或者说第i个数,之前排名比他大数量。
AC代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>
using namespace std;
const int maxn = (int)1e5+5;
typedef long long ll;
ll sum;
int c[maxn],val[maxn],tmp[maxn],rnk[maxn],n;
inline int lowbit (int a) {
return a & (-a);
}
inline void add (int idx, int num) {
while (idx <= n) {
c[idx] += num;
idx += lowbit(idx);
}
}
inline ll get_sum (int idx) {
ll ans = 0;
while (idx > 0) {
ans += c[idx];
idx -= lowbit(idx);
}
return ans;
}
void solve() {
//离散化
for (int i = 1; i <= n; i++) {
cin >> val[i];
tmp[i] = val[i];
}
sort(tmp + 1, tmp + 1 + n);
int len = unique(tmp + 1, tmp + 1 + n) - tmp - 1;
for (int i = 1; i <= n; i++) {
rnk[i] = lower_bound(tmp + 1, tmp + 1 + len, val[i]) - tmp; //rnk [1,...]
}
//从比较val的值转化成维护其rnk 找rnk逆序数
memset(c, 0, sizeof(c));
sum = 0;
for (int i = 1; i <= n; i++) {
add(rnk[i], 1);
sum += i - get_sum(rnk[i]);
}
cout << sum << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin >> n;
solve();
return 0;
}