-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
40 lines (36 loc) · 949 Bytes
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, delta: number): void {
for (; x <= this.n; x += x & -x) {
this.c[x] += delta;
}
}
query(x: number): number {
let s = 0;
for (; x > 0; x -= x & -x) {
s += this.c[x];
}
return s;
}
}
function getPermutationIndex(perm: number[]): number {
const mod = 1e9 + 7;
const n = perm.length;
const tree = new BinaryIndexedTree(n + 1);
let ans = 0;
const f: number[] = Array(n).fill(1);
for (let i = 1; i < n; ++i) {
f[i] = (f[i - 1] * i) % mod;
}
for (let i = 0; i < n; ++i) {
const cnt = perm[i] - 1 - tree.query(perm[i]);
ans = (ans + cnt * f[n - i - 1]) % mod;
tree.update(perm[i], 1);
}
return ans % mod;
}