Inversions
题意
- 给定 ,求出所有满足 的 的排列 的逆序对数之和。
- ,答案对 取模。
题解
首先考虑如何计算排列 的个数。
一个经典的做法是对 排序后答案就是 。
另一种思路是设 表示 的个数,那么答案就是 。
考虑枚举 求出 之间形成逆序对的方案数。
分类讨论:
- 。 从概率的角度考虑, 和 的概率是一样的,所以方案数就是总数除以 。
- 。 当 时没有贡献,因此将 变成 后方案数也是总数除以 。 变成 在 上的体现就是 这一段全部 。
- 。 用总方案数减去 的方案数,同理 ,将 变成 。
时间复杂度 ,不可接受。
考虑优化,记 ,则维护前缀积然后求和即可,树状数组实现时间复杂度 。
注意 可能为 ,分段计算贡献即可。
代码
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;
}