本质上是求逆序对个数,考虑将逆序对期望个数转为每一对 是逆序对的概率来求,然后把贡献拆一下,变成 ,其中 表示 取到 的概率。
考虑从小到大枚举 和 ,本质上求 ,然后用树状数组去维护单点加概率和后缀和查询。
现在需要去求一个人在长度为 的队伍中在第 个位置时被选中的概率,则概率为 ,推一下式子,得到 ,则求和部分是一个等比数列求和,则概率为 。
时间复杂度 。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
int n, m;
long double tree[N];
vector <int> a[N];
long double p;
long double qpow(long double x, int y) {
long double res = 1;
while(y) {
if(y & 1) res *= x;
x *= x;
y >>= 1;
}
return res;
}
void upd(int x, long double k) {
while(x < N) {
tree[x] += k;
x += x & -x;
}
}
long double qry(int x) {
long double ans = 0;
while(x) {
ans += tree[x];
x -= x & -x;
}
return ans;
}
int main() {
cin >> n >> m >> p;
for(int i = 1, x, y; i <= m; i++) {
cin >> x >> y;
a[x].push_back(y);
}
for(int i = 1; i <= n; i++) sort(a[i].begin(), a[i].end());
long double ans = 0;
for(int i = 1; i <= n; i++) {
for(int j = 0; j < a[i].size(); j++) {
int x = a[i][j];
long double res = p * qpow(1 - p, j) / (1 - qpow(1 - p, (int)a[i].size()));
long double res1 = qry(n - x);
ans += res * res1;
}
for(int j = 0; j < a[i].size(); j++) {
int x = a[i][j];
long double res = p * qpow(1 - p, j) / (1 - qpow(1 - p, (int)a[i].size()));
upd(n + 1 - x, res);
}
}
printf("%.2Lf", ans);
}