归并排序
void merge_sort(int l,int r) {
if (l == r) {
return;
}
int mid = l + r >> 1;
merge_sort(l, mid);
merge_sort(mid + 1, r);
int i = l, j = mid + 1, k = l;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) {
b[k++] = a[i++];
} else {
ans += mid - i + 1;
b[k++] = a[j++];
}
}
while (i <= mid) {
b[k++] = a[i++];
}r
while (j <= r) {
b[k++] = a[j++];
}
for (int i = l; i <= r; i++) {
a[i] = b[i];
}
}
树状数组
struct Node {
int x, y;
bool operator<(const Node &b) const {
return x < b.x;
}
}a[N];
int n;
int lowbit(int x) {
return x & -x;
}
void add(int x,int d) {
for (int i = x; i <= n; i += lowbit(i)) {
b[i] += d;
}
}
int sum(int x) {
int res = 0;
for (int i = x; i; i -= lowbit(i)) {
res += b[i];
}
return res;
}
int main() {
scanf("%d", &n);
for (int = 1; i <= n; i++) {
scanf("%d", a[i].x);
a[i].y = i;
}
sort(a + 1, a + 1 + n);
for (int i = 1; i <= n; i++) {
add(a[i].y, 1);
ans += i - sum(a[i].y);
}
printf("%d\n", ans);
}