Codeforces Round #388 (Div. 2), problem: (E) Inversions After Shuffle Solution in C/C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100000
/* Fenwick tree */
void update(long long *tt, int i, int n, int x) {
while (i < n) {
tt[i] += x;
i |= i + 1;
}
}
long long query(long long *tt, int i) {
long long sum = 0;
while (i >= 0) {
sum += tt[i];
i &= i + 1;
i–;
}
return sum;
}
struct element {
int a, i;
} aa[N];
int compare(const void *a, const void *b) {
struct element *pa = (struct element *) a;
struct element *pb = (struct element *) b;
return pb->a – pa->a;
}
int main() {
int n, i;
long long m;
double inv;
static long long tt[N];
scanf(“%d”, &n);
for (i = 0; i < n; i++) {
scanf(“%d”, &aa[i].a);
aa[i].i = i;
}
qsort(aa, n, sizeof *aa, compare);
m = (long long) n * (n + 1) / 2;
inv = 0;
for (i = 0; i < n; i++) {
inv += query(tt, aa[i].i) * m;
update(tt, aa[i].i, n, 1);
}
memset(tt, 0, n * sizeof *tt);
for (i = 0; i < n; i++) {
inv -= query(tt, aa[i].i) * (n – aa[i].i);
update(tt, aa[i].i, n, aa[i].i + 1);
}
for (i = 1; i <= n; i++)
inv += (long long) (n – i + 1) * i * (i – 1) / 4.0;
printf(“%.12lf\n”, inv / m);
return 0;
}