题意:有m个模式串,且每个模式串有一个权值,求一个长度不超过n的目标串,权值最大,如果有多个解输出长度最短,长度都相同选字典序最小的。
题解:n最大50,可以dp,f[i][j]表示长度为i的字符串当前节点是j的最大权值,s[i][j]表示长度为i当前节点是j的最优字符串解。ac自动机可以得到模式串的跳转表next[node][c]和到节点i的权值val[i],那么状态转移方程可得:f[i][next[j][k]] = max(f[i][next[j][k]],f[i - 1][j] + val[next[j][k]]),根据f[i][next[j][k]]的最大值里找最优字符串解。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1500;
const int SIGMA_SIZE = 26;
int Next[N][SIGMA_SIZE], val[N], fail[N], sz, n, m;
int f[55][N];
char word[N][15], s[55][N][55], res[55];
void init() {
memset(Next[0], 0, sizeof(Next[0]));
val[0] = 0;
sz = 1;
}
bool cmp(char *a, char *b) {
int len1 = strlen(a);
int len2 = strlen(b);
if (len1 != len2)
return len1 < len2;
return strcmp(a, b) < 0;
}
void insert(char *s, int v) {
int u = 0, len = strlen(s);
for (int i = 0; i < len; i++) {
int k = s[i] - 'a';
if (!Next[u][k]) {
memset(Next[sz], 0, sizeof(Next[sz]));
val[sz] = 0;
Next[u][k] = sz++;
}
u = Next[u][k];
}
val[u] = v;
}
void getFail() {
queue<int> Q;
fail[0] = 0;
for (int i = 0; i < SIGMA_SIZE; i++)
if (Next[0][i]) {
fail[Next[0][i]] = 0;
Q.push(Next[0][i]);
}
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int i = 0; i < SIGMA_SIZE; i++) {
if (!Next[u][i])
Next[u][i] = Next[fail[u]][i];
else {
fail[Next[u][i]] = Next[fail[u]][i];
Q.push(Next[u][i]);
}
}
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
init();
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++)
scanf("%s", word[i]);
int v;
for (int i = 1; i <= m; i++) {
scanf("%d", &v);
insert(word[i], v);
}
getFail();
memset(f, -1, sizeof(f));
f[0][0] = 0;
strcpy(s[0][0], "");
char temp[55];
int temp2 = 0;
strcpy(res, "");
for (int i = 1; i <= n; i++)
for (int j = 0; j < sz; j++) {
if (f[i - 1][j] < 0)
continue;
strcpy(temp, s[i - 1][j]);
int len = strlen(temp);
for (int k = 0; k < SIGMA_SIZE; k++) {
temp[len] = k + 'a';
temp[len + 1] = 0;
int vv = f[i - 1][j] + val[Next[j][k]];
if (f[i][Next[j][k]] < vv || f[i][Next[j][k]] == vv && cmp(temp, s[i][Next[j][k]])) {
f[i][Next[j][k]] = vv;
strcpy(s[i][Next[j][k]], temp);
if (f[i][Next[j][k]] > temp2 || f[i][Next[j][k]] == temp2 && cmp(temp, res)) {
temp2 = f[i][Next[j][k]];
strcpy(res, temp);
}
}
}
}
printf("%s\n", res);
}
return 0;
}