题目传送门
https://lydsy.com/JudgeOnline/problem.php?id=2085
题解
考虑暴力 DP 的做法。令 \(dp[i][j]\) 表示以 \(j\) 为开头的子串,并且已经总共出现 \(i\) 次的最小长度。
\[
dp[i][j] = \min_{k=1}^n\{dp[i-1][k] + len_j - LC(j, k) \}
\]
其中 \(LC(j, k)\) 表示最长的 \(j\) 的后缀等于 \(k\) 的前缀。
然后这个东西可以用矩阵来加速。
矩阵的定义就是先加再取 \(\min\)。
时间复杂度 \(O(n^3\log m)\)。
#include<bits/stdc++.h>
#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back
template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}
typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;
template<typename I> inline void read(I &x) {
int f = 0, c;
while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
x = c & 15;
while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
f ? x = -x : 0;
}
const int N = 200 + 7;
const int M = 1e5 + 7;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int base = 1997;
int n, m, mxl;
int len[N];
char s[N][M];
ull ha[N][M], bin[M];
struct Matrix {
ll a[N][N];
inline Matrix() { memset(a, 0x3f, sizeof(a)); }
inline Matrix(const int &x) {
memset(a, 0x3f, sizeof(a));
for (int i = 1; i <= n; ++i) a[i][i] = x;
}
inline Matrix operator * (const Matrix &b) {
Matrix c;
for (int k = 1; k <= n; ++k)
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
smin(c.a[i][j], a[i][k] + b.a[k][j]);
return c;
}
} A, B;
inline Matrix fpow(Matrix x, int y) {
Matrix ans(0);
for (; y; y >>= 1, x = x * x) if (y & 1) ans = ans * x;
return ans;
}
inline ull get_hash(ull *h, int l, int r) { return h[r] - h[l - 1] * bin[r - l + 1]; }
inline void work() {
bin[0] = 1;
for (int i = 1; i <= mxl; ++i) bin[i] = bin[i - 1] * base;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j) {
int cnt = 0;
for (int k = 1; k <= std::min(len[i], len[j]) - 1; ++k)
if (get_hash(ha[i], 1, k) == get_hash(ha[j], len[j] - k + 1, len[j])) smax(cnt, k);
A.a[j][i] = len[j] - cnt;
// dbg("i = %d, j = %d, l = %d\n", i, j, cnt);
}
for (int i = 1; i <= n; ++i) B.a[i][1] = len[i];//, dbg("len[%d] = %d\n", i, len[i]);
B = fpow(A, m - 1) * B;
// B = A * B;
ll ans = INF;
for (int i = 1; i <= n; ++i) smin(ans, B.a[i][1]);//, dbg("B.a[%d][1] = %lld\n", i, B.a[i][1]);
printf("%lld\n", ans);
}
inline void init() {
read(n), read(m);
for (int i = 1; i <= n; ++i) {
scanf("%s", s[i] + 1);
len[i] = strlen(s[i] + 1), smax(mxl, len[i]);
for (int j = 1; j <= len[i]; ++j) ha[i][j] = ha[i][j - 1] * base + (s[i][j] - 'a' + 1);
}
}
int main() {
#ifdef hzhkk
freopen("hkk.in", "r", stdin);
#endif
init();
work();
fclose(stdin), fclose(stdout);
return 0;
}
原文地址:https://www.cnblogs.com/hankeke/p/bzoj2085.html
时间: 2024-10-10 11:59:40