Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望
如果改变的是[L, R], 那么[L, R]内的逆序对数的期望为 len * (len - 1) / 2
所以我们的目标变成了, 求出所有区间内的逆序对之和, 这个用树状数组就能维护了。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 1e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} struct Bit { LL a[N]; void init() { memset(a, 0, sizeof(a)); } void modify(int x, int v) { for(int i = x; i < N; i += i & -i) a[i] += v; } LL sum(int x) { LL ans = 0; for(int i = x; i; i -= i & -i) ans += a[i]; return ans; } LL query(int L, int R) { if(L > R) return 0; return sum(R) - sum(L - 1); } }; int n, a[N]; Bit bit; LL totinv; int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); totinv += bit.query(a[i] + 1, n); bit.modify(a[i], 1); } bit.init(); LL ret1 = 0, ret2 = 0; for(LL i = 1; i <= n; i++) { ret1 += (n - i + 1) * bit.query(a[i] + 1, n); bit.modify(a[i], i); } double tmp1 = 2.0 * ret1 / n / (n + 1); for(LL i = 1; i <= n; i++) { LL cnt = n - i + 1; ret2 += i * (i - 1) / 2 * cnt; } double tmp2 = 1.0 * ret2 / n / (n + 1); printf("%.12f\n", totinv - tmp1 + tmp2); return 0; } /* */