题解:P6089 [JSOI2015] 非诚勿扰

· · 题解

本质上是求逆序对个数,考虑将逆序对期望个数转为每一对 (i,j) 是逆序对的概率来求,然后把贡献拆一下,变成 \sum d(a_i)d(a_j)[i<j\land a_i>a_j],其中 d(a_i) 表示 i 取到 a_i 的概率。

考虑从小到大枚举 i 和 a_i,本质上求 \sum\limits_{a_j>a_i} d(a_j),然后用树状数组去维护单点加概率和后缀和查询。

现在需要去求一个人在长度为 k 的队伍中在第 i 个位置时被选中的概率,则概率为 \sum (1-p)^{ak+i-1}p,推一下式子,得到 p(1-p)^{i-1}\sum (1-p)^{ak},则求和部分是一个等比数列求和,则概率为 p(1-p)^{i-1}\times \frac{(1-p)^{\infty}-1}{(1-p)^k-1}=\frac{p(1-p)^{i-1}}{1-(1-p)^k}。

时间复杂度 O(n\log n)。

:::info[代码]

#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);
}

:::