2020-01-15 09:38:21

$$\frac{i(n-j+1)}{\frac{n(n+1)}{2}}$$

$$P_{i,j}=\frac{i(n-j+1)}{n(n+1)}$$

\begin{aligned}E_1&=\sum_{i=1}^n\sum_{j=i+1}^nP_{i,j}\\&=\sum_{i=1}^n\sum_{j=i+1}^n\frac{i(n-j+1)}{n(n+1)}\\&=\sum_{i=1}^n\frac{i(n-i)(n-i+1)}{2n(n+1)}\\&=\frac{1}{2n(n+1)}\sum_{i=1}^ni(n-i)(n-i+1)\end{aligned}

\begin{aligned}&\frac{\frac{j(j-1)}{2}+\frac{(n-i)(n-i+1)}{2}-\frac{(j-i-1)(j-i)}{2}}{\frac{n(n+1)}{2}}\\=&\frac{j(j-1)+(n-i)(n-i+1)-(j-i-1)(j-i)}{n(n+1)}\\=&\frac{n^2+n-2ni-2i+2ij}{n(n+1)}\end{aligned}

$$P_{i,j}=[a_i>a_j]\frac{n^2+n-2ni-2i+2ij}{n(n+1)}$$

\begin{aligned}E_2&=\sum_{i=1}^n\sum_{j=i+1}^nP_{i,j}\\&=\sum_{i=1}^n\frac{n^2+n-2ni-2i+2ij}{n(n+1)}\\&=\frac{1}{n(n+1)}\sum_{i=1}^n\sum_{j=i+1}^n[a_i>a_j](n^2+n-2ni-2i+2ij)\end{aligned}

// ===================================
//   author: M_sea
//   website: http://m-sea-blog.com/
// ===================================
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#define re register
#define int long long
using namespace std;

inline int read() {
int X=0,w=1; char c=getchar();
while (c<'0'||c>'9') { if (c=='-') w=-1; c=getchar(); }
while (c>='0'&&c<='9') X=X*10+c-'0',c=getchar();
return X*w;
}

const int N=100000+10;

int n,a[N];

struct BIT {
int c[N];
inline void add(int x,int y) { for (;x<=n;x+=x&-x) c[x]+=y; }
inline int sum(int x) { int s=0; for (;x;x-=x&-x) s+=c[x]; return s; }
} C,S;

signed main() {
n=read();
for (re int i=1;i<=n;++i) a[i]=read();
double ans=0;
for (re int i=1;i<=n;++i) ans+=0.5*i*(n-i)*(n-i+1);
for (re int i=n;i;--i) {
ans+=C.sum(a[i]-1)*(n*n+n-2*i-2*n*i);
ans+=2*S.sum(a[i]-1)*i;
C.add(a[i],1),S.add(a[i],i);
}
printf("%.20lf\n",1.0*ans/n/(n+1));
return 0;
}
• star
首页