/*
----------------AC自动机+动态规划------------------
利用fail数组的跳转来构造转移方程
*/
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<cmath>
using namespace std;
#define ll long long
#define pi acos(-1)
const int maxn = 1500;
int trie[maxn][26]; //字典树
int color[maxn]; //标记终点
int id; //当前字典树中有几个节点
int fail[maxn]; //匹配失败时的跳转指针
int dp[55][maxn]; //dp[i][j]表示长度为i的字符串当前节点是j的最大权值
char s[55][maxn][55]; //s[i][j]表示长度为i当前节点是j的最优字符串解
char res[55];
char word[maxn][15]; //输入的模式串组
inline void insert(char *ss,int weight) //将字符串s插入字典树
{
int len = strlen(ss);
int p = 0; //从0节点开始
for(int i=0;i<len;++i)
{
int c = ss[i] - 'a';
if(!trie[p][c]) //没有边,就加边
{
memset(trie[id],0,sizeof(trie[id]));
color[id] = 0;
trie[p][c] = id++;
}
p = trie[p][c];
}
color[p] = weight;
}
inline void getfail() //利用BFS获取fail数组
{
queue<int>q; //利用BFS获取fail数组
for(int i=0;i<26;++i) //将第二层所有出现了的字母扔进队列
if(trie[0][i])
{
fail[trie[0][i]] = 0;
q.push(trie[0][i]);
}
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i=0;i<26;++i)
{
if(trie[u][i])
{
fail[trie[u][i]] = trie[fail[u]][i];
q.push(trie[u][i]);
}
else
trie[u][i] = trie[fail[u]][i];
}
}
}
inline int search(char *s) //模式串匹配--只能查出模式串是否出现
{
int len = strlen(s);
int ans = 0;
int p = 0;
for(int i=0;i<len;++i)
{
int c = s[i] - 'a';
p = trie[p][c];
for(int j=p;j&&color[j]!=-1;j=fail[j])
{
//一直向下寻找,直到匹配失败(失败指针指向根或者当前节点已找过
ans += color[j];
color[j] = -1; //将遍历过后的节点标记,防止重复计算
}
}
return ans;
}
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;
}
signed main()
{
int t;
int n,m;
scanf("%d",&t);
while(t--)
{
id = 1;
memset(trie[0],0,sizeof(trie[0]));
memset(color,0,sizeof(color));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i) scanf("%s",word[i]);
int weight;
for(int i=1;i<=m;++i)
{
scanf("%d",&weight);
insert(word[i],weight);
}
getfail();
memset(dp,-1,sizeof(dp));
dp[0][0] = 0;
strcpy(s[0][0],"");
strcpy(res,"");
char temp[55];
int temp2 = 0;
for(int i=1;i<=n;++i)
{
for(int j=0;j<id;++j)
{
if(dp[i-1][j]<0) continue;
strcpy(temp,s[i-1][j]);
int len = strlen(temp);
for(int k=0;k<26;++k)
{
temp[len] = k + 'a';
temp[len+1] = 0;
int vv = dp[i-1][j] + color[trie[j][k]];
if(dp[i][trie[j][k]]<vv||dp[i][trie[j][k]]==vv&&cmp(temp,s[i][trie[j][k]]))
{
dp[i][trie[j][k]] = vv;
strcpy(s[i][trie[j][k]],temp);
if(dp[i][trie[j][k]]>temp2||dp[i][trie[j][k]]==temp2&&cmp(temp,res))
{
temp2 = dp[i][trie[j][k]];
strcpy(res,temp);
}
}
}
}
}
printf("%s\n",res);
}
return 0;
}
03-22
518