|
1 | 1 | // Longest Subsequence Repeated k Times
|
2 |
| -#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++) |
| 2 | +#define FOR(i, a, b) for (long i = (a); i < (b); i++) |
3 | 3 | #define REP(i, n) FOR(i, 0, n)
|
4 |
| -#define ROF(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (b); --i >= (a); ) |
5 |
| -using pii = pair<int, int>; |
| 4 | +#define ROF(i, a, b) for (long i = (b); --i >= (a); ) |
6 | 5 |
|
7 | 6 | class Solution {
|
8 |
| - vector<pii> ab; |
9 | 7 | vector<array<int, 26>> nxt;
|
10 | 8 | string cur, ans;
|
11 |
| - int k; |
12 |
| - bool dfs(int st, int i) { |
13 |
| - bool ok = 0; |
14 |
| - for (auto &c: ab) { |
15 |
| - if (c.second == 0) continue; |
16 |
| - int j = nxt[i][c.first]; |
| 9 | + int freq[26] = {}, k; |
| 10 | + void dfs(int l, int i) { |
| 11 | + ROF(c, 0, 26) { |
| 12 | + if (freq[c] < k) continue; |
| 13 | + int j = nxt[i][c]; |
17 | 14 | if (j < 0) continue;
|
18 |
| - c.second--; |
19 |
| - cur.push_back('a'+c.first); |
20 |
| - ok |= dfs(st+1, j); |
21 |
| - cur.pop_back(); |
22 |
| - c.second++; |
| 15 | + |
| 16 | + freq[c] -= k; |
| 17 | + cur[l-1] = 'a'+c; |
| 18 | + REP(_, k-1) |
| 19 | + REP(x, l) { |
| 20 | + j = nxt[j][cur[x]-'a']; |
| 21 | + if (j < 0) goto out; |
| 22 | + } |
| 23 | + if (l > ans.size()) |
| 24 | + ans = cur.substr(0, l); |
| 25 | + dfs(l+1, nxt[i][c]); |
| 26 | +out: |
| 27 | + freq[c] += k; |
23 | 28 | }
|
24 |
| - if (ok) |
25 |
| - return true; |
26 |
| - if (st <= ans.size()) |
27 |
| - return false; |
28 |
| - REP(_, k-1) |
29 |
| - for (char c: cur) { |
30 |
| - i = nxt[i][c-'a']; |
31 |
| - if (i < 0) return false; |
32 |
| - } |
33 |
| - ans = cur; |
34 |
| - return true; |
35 | 29 | }
|
36 | 30 | public:
|
37 | 31 | string longestSubsequenceRepeatedK(string s, int k) {
|
38 |
| - this->k = k; |
39 |
| - int freq[26] = {}, n = s.size(); |
| 32 | + int n = s.size(); |
40 | 33 | for (char c: s)
|
41 | 34 | freq[c-'a']++;
|
42 |
| - ROF(c, 0, 26) |
43 |
| - if (freq[c] >= k) |
44 |
| - ab.emplace_back(c, freq[c]/k); |
45 |
| - |
46 | 35 | nxt.resize(n+1);
|
47 | 36 | REP(c, 26)
|
48 | 37 | nxt[n][c] = -1;
|
49 | 38 | ROF(i, 0, n) {
|
50 | 39 | nxt[i] = nxt[i+1];
|
51 | 40 | nxt[i][s[i]-'a'] = i+1;
|
52 | 41 | }
|
53 |
| - dfs(0, 0); |
| 42 | + this->k = k; |
| 43 | + cur.resize(n/k); |
| 44 | + dfs(1, 0); |
54 | 45 | return ans;
|
55 | 46 | }
|
56 | 47 | };
|
0 commit comments