Problem
This is just another word game. You are given a dictionary of words. Each of the word has a weight W, which is an integer value. You are given another string S. Initially your score is zero. In each turn you can mark some consecutive characters. If these consecutive characters create a word in the given dictionary, corresponding weight will be added to your score, otherwise a penalty P will be subtracted word length times from your score. Here word length is number of character in a word, and P is an integer value. What is the maximum score you can gain?
Note that your have to make a move until all characters of S are marked, and you cannot mark one character more than once.
Input
Input will start with an integer number T (T≤20), which indicates the number of test case. Each test case starts with two integer N (N ≤ 10000) and P (0 ≤ P ≤ 10000). Here N is the number of words in the dictionary and P is the value of Penalty. Each of the next N lines will contain a word and corresponding integer weight W (0 ≤ W ≤ 10000). No word of this dictionary will contain more than 100 characters, and a word will only contain lower case alphabet (‘a’, ‘b’, … ,’z’). The last line of the input will contain string S. S will not contain more than 10000 characters, and will contain only lower case letters.
Output
For each test case you have to output one line which “Case #:” where # is replaced by the case number, then a space, then the maximum score.
Sample Input
|
|
Output for Sample Input
|
|
Solution
題目描述:
給一個主子串 S,可以由其他小字串組合而成,這些小字串可以重複使用,每次使用可以得到相對應的單位獲益,但它們彼此之間不能重疊,如果 S 有一個字符沒有匹配,將會被罰款 W 單位。
求一個最高獲益的值為何?
題目解法:
由於考慮 dp[i]
已經匹配長度為 i 的時候,轉移會在字串匹配的時候速度非常慢,因此可以利用字串匹配的特性,對於所有小字串建一個 trie,接著建造出 AC 自動機,可以藉由失敗指針中快速找到當前有多少可以轉移的字符串可以串接。
但問題可能會在小字串長度太長效率下降,AC 只是剛好!也有人直接用 trie 搭配走訪就過去了,對於位置 i,從 root 開始往下走,一直走到位置 j,並且轉移,直到 trie 沒辦法走下去,保證不會有其他匹配情況。
|
|