Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P3502 [POI2010]CHO-Hamsters

P3502 [POI2010]CHO-Hamsters

考虑DP,用KMP计算出将一个串接在一个串后面增加的代价,那么问题转化为有向图上经过 $m$ 条边的最短路,可以矩阵加速。

查看代码
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
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
template <class Type>
void chkmin (Type &x, Type k)
{
k < x && (x = k);
}
typedef long long LL;
const int N = 210;
const LL inf = 1e14;
int n, m;
vector <int> nxt[N];
string str[N];
struct Matrix
{
int n, m;
LL w[N][N];
Matrix (int _n, int _m)
{
n = _n, m = _m;
}
friend Matrix operator*(Matrix x, Matrix y)
{
Matrix res(x.n, y.m);
for (int i = 0; i <= res.n; i++)
for (int j = 0; j <= res.m; j++)
{
res.w[i][j] = inf;
for (int k = 0; k <= x.m; k++)
chkmin(res.w[i][j], x.w[i][k] + y.w[k][j]);
}
return res;
}
friend Matrix operator^(Matrix b, int k)
{
Matrix res = b;
k--;
while (k)
{
k & 1 && (res = res * b, 0);
b = b * b;
k >>= 1;
}
return res;
}
};
int main ()
{
read(n), read(m);
static Matrix A(n, n);
for (int i = 0; i <= n; i++)
A.w[i][0] = inf;
for (int k = 1; k <= n; k++)
{
cin >> str[k];
A.w[0][k] = str[k].size();
nxt[k].resize(str[k].size() + 1);
nxt[k][1] = 0;
for (int i = 1, j = 0; i < str[k].size(); i++)
{
while (j && str[k][i] != str[k][j])
j = nxt[k][j];
j += str[k][i] == str[k][j];
nxt[k][i + 1] = j;
}
A.w[k][k] = str[k].size() - nxt[k][str[k].size()];
}
for (int l = 1; l <= n; l++)
for (int r = 1; r <= n; r++)
{
if (l == r)
continue;
int j = 0;
for (int i = 0; i < str[r].size(); i++)
{
while (j && str[r][i] != str[l][j])
j = nxt[l][j];
j += str[r][i] == str[l][j];
}
A.w[l][r] = str[r].size() - j;
}
A = A ^ m;
LL res = inf;
for (int i = 1; i <= n; i++)
chkmin(res, A.w[0][i]);
write(res);
return 0;
}