描述

Recently George is preparing for the Graduate Record Examinations (GRE for short). Obviously the most important thing is reciting the words.
Now George is working on a word list containing N words.
He has so poor a memory that it is too hard for him to remember all of the words on the list. But he does find a way to help him to remember. He finds that if a sequence of words has a property that for all pairs of neighboring words, the previous one is a substring of the next one, then the sequence of words is easy to remember.
So he decides to eliminate some words from the word list first to make the list easier for him. Meantime, he doesn’t want to miss the important words. He gives each word an importance, which is represented by an integer ranging from -1000 to 1000, then he wants to know which words to eliminate to maximize the sum of the importance of remaining words. Negative importance just means that George thought it useless and is a waste of time to recite the word.
Note that although he can eliminate any number of words from the word list, he can never change the order between words. In another word, the order of words appeared on the word list is consistent with the order in the input. In addition, a word may have different meanings, so it can appear on the list more than once, and it may have different importance in each occurrence.

Input

The first line contains an integer $T$($1 \le T \le 50$), indicating the number of test cases.
Each test case contains several lines.
The first line contains an integer $N$($1 \le N \le 2 * 10^4$), indicating the number of words.
Then $N$ lines follows, each contains a string $S_i$ and an integer $W_i$, representing the word and its importance. $S_i$ contains only lowercase letters.
You can assume that the total length of all words will not exceeded $3 * 10^5$.

Output

For each test case in the input, print one line: “Case #X: Y”, where X is the test case number (starting with 1) and Y is the largest importance of the remaining sequence of words.

思路

• 类比最长（最大权）上升子序列，我们很容易写出这样一个DP式子($dp[i]$表示以第$i$个串结尾的最大价值)：$$dp[i] = \max(dp[j]) + w[i]$$其中$j < i$且$s_j$是$s_i$的子串。
• 可以想到用AC自动机来维护这些DP值，这样对于一个串就可以做到线性时间的转移。
• 那么如何在AC自动机上更新当前串的DP值呢，显然Fail指针指向它的结点都需要被更新。也就是说，Fail指针反向后构成的树中该结点的子树都应该被更新。
• 所以我们搞出Fail树的DFS序之后拿个线段树搞一下区间更新就好了。
• 手滑开了$10^6$的数组，就MLE了。

0%