【题目链接】
【思路要点】
- 补档博客,无题解。
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 200005 #define MAXC 4 #define MAXLOG 63 const long long INF = 1.5e18; template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } long long matrix[MAXLOG][MAXC][MAXC]; long long vec[1][MAXC], tmp[1][MAXC]; void chkmin(long long &x, long long y) { x = min(x, y); } struct Suffix_Automaton { int child[MAXN][MAXC]; int father[MAXN], depth[MAXN], type[MAXN]; long long dp[MAXN][MAXC]; bool visited[MAXN]; int size, root, last; int new_node(int dep, int t) { type[size] = t; depth[size] = dep; father[size] = 0; memset(child[size], 0, sizeof(child[size])); return size++; } void init() { size = 0; root = last = new_node(0, 0); } void Extend(int ch) { int p = last, np = new_node(depth[p] + 1, ch); while (child[p][ch] == 0) { child[p][ch] = np; p = father[p]; } if (child[p][ch] == np) father[np] = root; else { int q = child[p][ch]; if (depth[q] == depth[p] + 1) father[np] = q; else { int nq = new_node(depth[p] + 1, ch); father[nq] = father[q]; father[q] = father[np] = nq; memcpy(child[nq], child[q], sizeof(child[q])); while (child[p][ch] == q) { child[p][ch] = nq; p = father[p]; } } } last = np; } void insert(char *s) { int len = strlen(s + 1); for (int i = 1; i <= len; i++) Extend(s[i] - 'A'); } void dfs(int root) { visited[root] = true; for (int i = 0; i < MAXC; i++) { if (!visited[child[root][i]]) dfs(child[root][i]); if (child[root][i] == 0) dp[root][i] = 1; else { for (int j = 0; j < MAXC; j++) chkmin(dp[root][j], dp[child[root][i]][j] + 1); } } } void getmatrix() { for (int i = 0; i < size; i++) for (int j = 0; j < MAXC; j++) dp[i][j] = INF; dfs(root); for (int i = 0; i < MAXC; i++) for (int j = 0; j < MAXC; j++) matrix[0][i][j] = dp[child[root][i]][j]; } } SAM; char s[MAXN]; int main() { long long n; read(n); scanf("\n%s", s + 1); SAM.init(); SAM.insert(s); SAM.getmatrix(); for (int p = 1; p < MAXLOG; p++) { for (int i = 0; i < MAXC; i++) for (int j = 0; j < MAXC; j++) matrix[p][i][j] = INF; for (int i = 0; i < MAXC; i++) for (int j = 0; j < MAXC; j++) for (int k = 0; k < MAXC; k++) chkmin(matrix[p][i][j], min(INF, matrix[p - 1][i][k] + matrix[p - 1][k][j])); } long long ans = 0; for (int p = MAXLOG - 1; p >= 0; p--) { for (int i = 0; i < MAXC; i++) tmp[0][i] = INF; for (int i = 0; i <= 0; i++) for (int j = 0; j < MAXC; j++) for (int k = 0; k < MAXC; k++) chkmin(tmp[i][j], min(INF, vec[i][k] + matrix[p][k][j])); bool flg = false; for (int i = 0; i < MAXC; i++) if (tmp[0][i] <= n) flg = true; if (flg) { for (int i = 0; i < MAXC; i++) vec[0][i] = tmp[0][i]; ans += 1ll << p; } } for (int i = 0; i < MAXC; i++) if (vec[0][i] < n) { ans++; break; } cout << ans << endl; return 0; }