-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-the-index-of-permutation.cpp
111 lines (96 loc) · 2.81 KB
/
find-the-index-of-permutation.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Time: O(nlogn)
// Space: O(n)
// bit, fenwick tree, combinatorics
class Solution {
private:
static const uint32_t MOD = 1e9 + 7;
public:
int getPermutationIndex(vector<int>& perm) {
vector<int> fact(size(perm) + 1);
fact[0] = 1;
for (int i = 0; i + 1 < size(fact); ++i) {
fact[i + 1] = (static_cast<int64_t>(i + 1) * fact[i]) % MOD;
}
int result = 0;
BIT bit(size(perm));
for (int i = 0; i < size(perm); ++i) {
result = (result + (static_cast<int64_t>((((perm[i] - 1) - bit.query((perm[i] - 1) - 1)) % MOD + MOD) % MOD) * fact[(size(perm) - 1) - i] % MOD)) % MOD;
bit.add(perm[i] - 1, +1);
}
return result;
}
private:
class BIT {
public:
BIT(int n) : bit_(n + 1) { // 0-indexed
}
void add(int i, int val) {
++i;
for (; i < size(bit_); i += lower_bit(i)) {
bit_[i] = (bit_[i] + val) % MOD;
}
}
int query(int i) const {
++i;
int total = 0;
for (; i > 0; i -= lower_bit(i)) {
total = (total + bit_[i]) % MOD;
}
return total;
}
private:
inline int lower_bit(int i) const {
return i & -i;
}
vector<int> bit_;
};
};
// Time: O(nlogn)
// Space: O(n)
// bit, fenwick tree, combinatorics
class Solution2 {
private:
static const uint32_t MOD = 1e9 + 7;
public:
int getPermutationIndex(vector<int>& perm) {
vector<int> fact = {1, 1};
const auto& factorial = [&](int n) {
while (size(fact) <= n) { // lazy initialization
fact.emplace_back((static_cast<int64_t>(fact.back()) * size(fact)) % MOD);
}
return fact[n];
};
int result = 0;
BIT bit(size(perm));
for (int i = 0; i < size(perm); ++i) {
result = (result + (static_cast<int64_t>((((perm[i] - 1) - bit.query((perm[i] - 1) - 1)) % MOD + MOD) % MOD) * factorial((size(perm) - 1) - i) % MOD)) % MOD;
bit.add(perm[i] - 1, +1);
}
return result;
}
private:
class BIT {
public:
BIT(int n) : bit_(n + 1) { // 0-indexed
}
void add(int i, int val) {
++i;
for (; i < size(bit_); i += lower_bit(i)) {
bit_[i] = (bit_[i] + val) % MOD;
}
}
int query(int i) const {
++i;
int total = 0;
for (; i > 0; i -= lower_bit(i)) {
total = (total + bit_[i]) % MOD;
}
return total;
}
private:
inline int lower_bit(int i) const {
return i & -i;
}
vector<int> bit_;
};
};