UVA 1401 Remember the Word

来源:互联网 发布:取消电视软件自动升级 编辑:程序博客网 时间:2024/04/26 16:31

Neal is very curious about combinatorial problems, and now here comes a problem about words. Knowing that Ray has a photographic memory and this may not trouble him, Neal gives it to Jiejie.

Since Jiejie can't remember numbers clearly, he just uses sticks to help himself. Allowing for Jiejie's only 20071027 sticks, he can only record the remainders of the numbers divided by total amount of sticks.

The problem is as follows: a word needs to be divided into small pieces in such a way that each piece is from some given set of words. Given a word and the set of words, Jiejie should calculate the number of ways the given word can be divided, using the words in the set.

Input 

The input file contains multiple test cases. For each test case: the first line contains the given word whose length is no more than 300 000.

The second line contains an integer S , 1$ \le$S$ \le$4000 .

Each of the following S lines contains one word from the set. Each word will be at most 100 characters long. There will be no two identical words and all letters in the words will be lowercase.

There is a blank line between consecutive test cases.

You should proceed to the end of file.

Output 

For each test case, output the number, as described above, from the task description modulo 20071027.

Sample Input 

abcd 4 a b cd ab

Sample Output 

Case 1: 2


给定字符串,给你一些单词,问有多少种拼法。

字典树+递推


#include<cstdio>#include<cstring>#include<iostream>#include<string>#include<algorithm>#include<math.h>using namespace std;char s[400000], ss[105];int f[400000][27], t, tot, a[400000], n;int main(){int b = 0;while (~scanf("%s", s)){cin >> t;tot = 0;memset(f[0], 0, sizeof(f[0]));memset(a, 0, sizeof(a));for (int i = 1; i <= t; i++){scanf("%s", ss);int j = 0, k = 0;while (ss[k] != '\0'){if (f[j][ss[k] - 'a'] == 0){tot++;memset(f[tot], 0, sizeof(f[tot]));j = f[j][ss[k] - 'a'] = tot;}else j = f[j][ss[k] - 'a'];k++;}f[j][26] = 1;}a[0] = 1;for (int i = 0; s[i] != '\0'; i++){int j = 0, k = 0;while (s[i + k] != '\0'&&f[j][s[i + k] - 'a']){j = f[j][s[i + k] - 'a'];k++;if (f[j][26]) a[i + k] = (a[i + k] + a[i]) % 20071027;}if (s[i + 1] == '\0') n = a[i + 1];}cout << "Case " << ++b << ": " << n << endl;}return 0;}
字典树的初始化是用到的时候才出始的,负责容易超时。

0 0
原创粉丝点击