Neal is very curious about combinatorial problems, and now here comes a problem about words. Know- ing 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.
分析:d(i)表示从第i字符开始的字符串(即后缀S【i,len】)的分解方案数,则d(i) = sum{ d(i + len(x) | 单词x是S【i,len】的前缀}。直接枚举会超时.应将所有的单词组成一棵前缀树Trie,然后查找。
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int N = 4000*100 +5,SIZE = 26, MOD = 20071027;
struct Trie{
int ch[N][SIZE];
int val[N];
int sz; // 结点总数
// 初始时只有一个根结点
void clear(){
sz = 1;
memset(ch[0],0,sizeof(ch[0]));
}
// 字符c的编号
int idx(char c){
return c - 'a';
}
// 插入字符串s,附加信息为v。注意v必须非0,因为0代表“本结点不是单词结点”
void insert(const char *s, int v){
int u = 0, n = strlen(s);
for(int i = 0; i < n; i++){
int c = idx(s[i]);
if( !ch[u][c]){ // 结点不存在
memset(ch[sz], 0,sizeof(ch[sz])); //新建一个size节点
val[sz] = 0; // 中间结点的附加信息为0
ch[u][c] = sz++; // //指向新建的子节点idx = size
}
u = ch[u][c];
}
val[u] = v; // 字符串的最后一个字符的附加信息为v
}
// 找字符串s的长度不超过len的前缀
void find_prefixes(const char *s,int len,vector<int>& ans){
int u = 0;
for(int i = 0; i < len; i++){
if( s[i] == '\0') break;
int c = idx(s[i]);
if( !ch[u][c]) break; //找不到对应的char
u = ch[u][c];
if( val[u])
ans.push_back(val[u]); // 找到一个前缀
}
}
};
const int TEXT = 300000 +5, WORD = 100 +5;
char text[TEXT], word[WORD];
Trie trie;
int d[TEXT];
int main(int argc, char** argv) {
int kase = 0;
while( scanf("%s", text) == 1){
int n;
scanf("%d",&n);
trie.clear();
while( n--){
scanf("%s",word);
trie.insert(word, strlen(word)); //附加信息为插入字符串的长度
}
int len = strlen(text);
memset(d, 0, sizeof(d));
d[len] = 1;
for(int i = len - 1; i >= 0; i--){
vector<int> p;
trie.find_prefixes(text+i, len-i, p);
for(int j = 0; j < p.size(); j++)
d[i] = (d[i] + d[i+p[j]]) % MOD;
}
printf("Case %d: %d\n",++kase, d[0]);
}
return 0;
}