标签:
2 7 2 love ever 5 5 5 1 ab 5
lovever abab
1 #include <bits/stdc++.h> 2 using namespace std; 3 using PII = pair<int,int>; 4 const int maxn = 510; 5 6 struct Trie{ 7 int ch[maxn][26],fail[maxn],cnt[maxn],tot; 8 int dp[maxn][maxn]; 9 PII path[maxn][maxn]; 10 int newnode(){ 11 memset(ch[tot],0,sizeof ch[tot]); 12 fail[tot] = cnt[tot] = 0; 13 return tot++; 14 } 15 void init(){ 16 tot = 0; 17 newnode(); 18 } 19 void insert(char *str,int val,int rt = 0){ 20 for(int i = 0; str[i]; ++i){ 21 int &x = ch[rt][str[i]-‘a‘]; 22 if(!x) x = newnode(); 23 rt = x; 24 } 25 cnt[rt] += val; 26 } 27 void build(int rt = 0){ 28 queue<int>q; 29 for(int i = 0; i < 26; ++i) 30 if(ch[rt][i]) q.push(ch[rt][i]); 31 while(!q.empty()){ 32 rt = q.front(); 33 q.pop(); 34 cnt[rt] += cnt[fail[rt]]; 35 for(int i = 0; i < 26; ++i){ 36 int &x = ch[rt][i],y = ch[fail[rt]][i]; 37 if(x){ 38 fail[x] = y; 39 q.push(x); 40 }else x = y; 41 } 42 } 43 } 44 void solve(int n){ 45 memset(dp,0,sizeof dp); 46 for(int i = n; i; --i){ 47 for(int j = 0; j < tot; ++j){ 48 for(int k = 0; k < 26; ++k){ 49 int x = ch[j][k],tmp = dp[i+1][x] + cnt[x]; 50 if(tmp > dp[i][j]){ 51 dp[i][j] = tmp; 52 path[i][j] = PII(x,k); 53 } 54 } 55 } 56 } 57 int pos = n + 1,ans = 0,st = 0; 58 for(int i = n + 1; i; --i) 59 if(dp[i][0] > ans) ans = dp[pos = i][0]; 60 for(int i = pos; i <= n; ++i){ 61 printf("%c",path[i][st].second + ‘a‘); 62 st = path[i][st].first; 63 } 64 putchar(‘\n‘); 65 } 66 }ac; 67 char str[maxn][maxn]; 68 int main(){ 69 int kase,n,m,val; 70 scanf("%d",&kase); 71 while(kase--){ 72 scanf("%d%d",&n,&m); 73 for(int i = 0; i < m; ++i) 74 scanf("%s",str[i]); 75 ac.init(); 76 for(int i = 0; i < m; ++i){ 77 scanf("%d",&val); 78 ac.insert(str[i],val); 79 } 80 ac.build(); 81 ac.solve(n); 82 } 83 return 0; 84 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4940619.html