agc023_e Inversions

· · 题解

Inversions

题意

题解

首先考虑如何计算排列 p 的个数。

一个经典的做法是对 a 排序后答案就是 \prod_{i=1}^n (a_i - i + 1)。

另一种思路是设 c_i 表示 a_{k} \ge i 的个数,那么答案就是 \prod_{i=1}^n (c_i - (n - i))。

考虑枚举 i,j(i<j) 求出 i,j 之间形成逆序对的方案数。

分类讨论:

时间复杂度 \mathcal O(n^2),不可接受。

考虑优化,记 d_i = \frac {c_i - 1 - (n-i)}{c_i - (n-i)},则维护前缀积然后求和即可,树状数组实现时间复杂度 \mathcal O(n \log n)。

注意 d_i 可能为 0,分段计算贡献即可。

代码

const int N = 2e5 + 7;
const modint v2 = (modint)1 / 2;
int n, a[N], c[N], s0[N], p0[N];
modint d[N], vd[N], c1[N], c2[N], tot = 1, ans;

inline void add(int x, modint w) {
    while (x <= n) c1[x] += w, c2[x] += 1, x += x & -x;
}

inline modint ask(modint *c, int x) {
    modint ret = 0;
    while (x) ret += c[x], x -= x & -x;
    return ret;
}

int main() {
    rd(n), rda(a, n);
    for (int i = 1; i <= n; i++) ++c[a[i]];
    for (int i = n - 1; i; i--) c[i] += c[i+1];
    for (int i = 1; i <= n; i++) tot *= c[i] -= n - i;
    if (!tot) return print(0), 0;
    p0[0] = 1, d[0] = 1;
    for (int i = 1; i <= n; i++) {
        modint x = (modint)(c[i] - 1) / c[i];
        if (!x) s0[i] = s0[i-1] + 1, p0[s0[i]] = i, d[i] = d[i-1];
        else s0[i] = s0[i-1], d[i] = d[i-1] * x;
        vd[i] = 1 / d[i];
    }
    for (int i = 1; i <= n; i++)
        ans += (ask(c1, a[i]) - ask(c1, p0[s0[a[i]]] - 1)) * d[a[i]] * tot * v2, add(a[i], vd[a[i]]);
    for (int i = 1; i <= n; ++i) c1[i] = c2[i] = 0;
    for (int i = n; i; i--)
        ans += ask(c2, a[i] - 1) * tot - (ask(c1, a[i] - 1) - ask(c1, p0[s0[a[i]]] - 1)) * d[a[i]] * tot * v2, add(a[i], vd[a[i]]);
    print(ans.x);
    return 0;
}