康托展开

题目链接

题目

求一个排列在\(1\)~\(N\)的全排列中的排名。

解析

从第一个数开始考虑,比它小的排列第一个数一定比它小,设为\(k\)个。
后面的数可以乱排,方案数是\(k\times (n-1)!\)
后面的数同理,不能再用前面出现的数。
每一次都要找比当前数小的数个数,用权值树状数组维护。
时间复杂度\(\mathjaxcal{O}(n\log n)\)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;

const int MOD = 998244353, N = 1e6 + 5;
int n, a[N], tr[N], fac[N];

void upd(int x, int v) {for (; x <= n; x += x & -x) tr[x] += v;}
int qry(int x) {int res = 0; for (; x; x -= x & -x) res += tr[x]; return res;}
int qry(int x, int y) {return qry(y) - qry(x - 1);}

int main() {
scanf("%d", &n);
fac[0] = 1;
for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * 1ll * i % MOD;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), upd(a[i], 1);
int res = 1;
for (int i = 1; i <= n; i++) {
res = (res + fac[n - i] * 1ll * qry(a[i] - 1) % MOD) % MOD;
upd(a[i], -1);
}
printf("%d\n", res);
return 0;
}