NEU 1007 (字典树 DP)

1007: English Game

时间限制: 1 Sec   内存限制: 128 MB
提交: 294   解决: 64
[ 提交][ 状态][ 讨论版]

题目描述

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.

输入

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.

输出

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

样例输入

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

样例输出

8
7
5
40
-1


题意:把一个字符串用几个子串表示,求最大的权值.

设dp(i)表示i位之前的字符串都处理完的最大权值,那么dp(i+len[j])=max (dp(i+len[j]), dp(i)+val[j]),其中

i+1~i+len[j]这一段等于子串j,那么就可以用字典树存下原本所有的子串,然后每次从i开始从字典树的上面

往下扫就可以了.

#include <bits/stdc++.h>
using namespace std;
#define maxn 1111

struct node {
    int next[33];
    long long num;
}tree[31111];
int cnt;
char a[11111], s[33];
int n;
long long val;
long long dp[11111];

void init () {
    memset (tree, -1, sizeof tree);
    cnt = 0;
}

void add () {
    int l = strlen (s);
    int p = 0;
    for (int i = 0; i < l; i++) {
        int id = s[i]-'a';
        if (tree[p].next[id] == -1) {
            tree[p].next[id] = ++cnt;
        }
        p = tree[p].next[id];
    }
    tree[p].num = max (tree[p].num, val);
}

int main () {
    //freopen ("in.txt", "r", stdin);
    while (scanf ("%d%s", &n, a+1) == 2) {
        a[0] = '.';
        init ();
        for (int i = 0; i < n; i++) {
            scanf ("%s%lld", s, &val);
            add ();
        }
        memset (dp, -1, sizeof dp);
        dp[0] = 0;
        int l = strlen (a);
        l--;
        for (int i = 0; i < l; i++) {
            if (dp[i] == -1)
                continue;
            int p = 0;
            for (int j = i+1; j <= l; j++) {
                int id = a[j]-'a';
                if (tree[p].next[id] == -1)
                    break;
                if (tree[p].next[id] != -1 && tree[tree[p].next[id]].num != -1) {
                    dp[j] = max (dp[j], dp[i]+tree[tree[p].next[id]].num);
                }
                p = tree[p].next[id];
            }
        }
        printf ("%lld\n", dp[l] == 0 ? -1 : dp[l]);
    }
    return 0;
}


你可能感兴趣的:(NEU 1007 (字典树 DP))