Leetcode 1830. Minimum Number of Operations to Make String Sorted

挺神秘的一个题,题意自己看吧 https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/

先写一个暴力做法,然后找规律。需要用到快速幂。太麻烦了,懒得讲了。

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
class Solution {
int ksm(int a, int b, int c) {
int res = 1;
while (b > 0) {
if (b & 1) res = (long long)res * a % c;
a = (long long) a * a % c;
b >>= 1;
}
return res;
}

int get_ans(string s) {
int n = s.length();
int mo = 1000000007;
vector<int> f(n + 1);
vector<int> ni(n + 1);
f[0] = 1;
f[1] = 1;
ni[0] = 1;
ni[1] = 1;
for (int i = 2; i <= n; i++) {
f[i] = (long long) f[i - 1] * i % mo;
ni[i] = ksm(f[i], mo - 2, mo);
}
int ans = 0;
vector<int> num(26);
num[s[s.length() - 1] - 'a']++;
for (int now = s.length() - 2; now >= 0; now--) {
num[s[now] - 'a']++;
int tmp = f[s.length() - now - 1];
for (int j = 0; j < 26; j++) {
tmp = (long long) tmp * ni[num[j]] % mo;
}
for (int i = s[now] - 'a' - 1; i >= 0; i--) {
if (num[i] == 0) continue;
int qq = (long long) tmp * num[i] % mo;
ans = (ans + qq) % mo;
}
}
return ans % mo;
}

public:
int makeStringSorted(string s) {
return get_ans(s);
}
};