NBUT 1222 English Game 2010辽宁省赛

时间:2022-05-21 05:27:27

Time limit 1000 ms

Memory limit 131072 kB

This English game is a simple English words connection game.

The rules are as follows: there are N English words in a dictionary, and every word has its own weight v. There is a weight if the corresponding word is used. Now there is a target string X. You have to pick some words in the dictionary, and then connect them to form X. At the same time, the sum weight of the words you picked must be the biggest.

Input

There are several test cases. For each test, N (1<=n<=1000) and X (the length of x is not bigger than 10000) are given at first. Then N rows follow. Each row contains a word wi (the length is not bigger than 30) and the weight of it. Every word is composed of lowercases. No two words in the dictionary are the same.

Output

For each test case, output the biggest sum weight, if you could not form the string X, output -1.

Sample Input

1 aaaa
a 2
3 aaa
a 2
aa 5
aaa 6
4 abc
a 1
bc 2
ab 4
c 1
3 abcd
ab 10
bc 20
cd 30
3 abcd
cd 100
abc 1000
bcd 10000

Sample Output

8
7
5
40
-1 用给的每个小字符串的价值拼出给的大字符串的最大价值 我自己还不会,先记一下同校大牛的代码,再研究
 #include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;
const int N = ;
struct node
{
int l,r,v;
int nt;
}p[];
int h[],cnt;
void add(int l,int r,int v)
{
p[++cnt].l = l;
p[cnt].r = r;
p[cnt].v = v;
p[cnt].nt = h[l];
h[l]=cnt;
} char s[];
char c[][];
int dp[];
int l[],v[],n,len; int next[];
int slen; void getNext(int x)
{
int j, k;
j = ; k = -; next[] = -;
while(j < l[x])
if(k == - || c[x][j] == c[x][k])
next[++j] = ++k;
else
k = next[k];
}
void KMP_Count(int x)
{
int ans = ;
int i, j = ; if(slen == && l[x] == )
{
if(s[] == c[x][])
add(,,v[x]);
else return;
}
getNext(x);
for(i = ; i < slen; i++)
{
while(j > && s[i] != c[x][j])
j = next[j];
if(s[i] == c[x][j])
j++;
if(j == l[x])
{
add(i-l[x]+,i+,v[x]);
j = next[j];
}
}
}
int main()
{
while(scanf("%d%s",&n,s)!=EOF)
{
cnt = ;
memset(h,,sizeof(h));
slen = len = strlen(s);
memset(dp,-,sizeof(dp));
dp[]=;
for(int i=;i<=n;i++)
{
scanf("%s%d",c[i],&v[i]);
l[i] = strlen(c[i]);
KMP_Count(i);
}
for(int i=;i<len;i++)
{
if(dp[i]==-) continue;
for(int j=h[i];j>;j=p[j].nt)
{
dp[p[j].r] = max(dp[p[j].r], dp[i]+p[j].v);
}
}
printf("%d\n",dp[len]);
}
return ;
}