您的位置:首页 > 其它

字典树模板题(la3942)

2017-07-27 20:40 375 查看
Neal is very curious about combinatorial problems, and now here comes a problem about words. Kn
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 Jie
only 20071027 sticks, he can only record the remainders of the numbers divided by total amoun
sticks.
The problem is as follows: a word needs to be divided into small pieces in such a way that e
piece is from some given set of words. Given a word and the set of words, Jiejie should calculate
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 w
whose length is no more than 300 000.
The second line contains an integer S, 1 ≤ S ≤ 4000.
Each of the following S lines contains one word from the set. Each word will be at most
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 20071
Sample Input
abcd
4 a b
cd
ab
Sample Output
Case 1: 2

首先可以想到dp的思想:

dp[i]=sum{dp[i+len(x)]|x是s...l的前缀}

前缀的搜索可以用字典树,最多搜索100遍就可以了

抄了刘老师的板子,感觉还不错。

#include<bits/stdc++.h>
#define maxs 26
#define maxn 30000
#define mod 20071027
#define maxnode 401000
using namespace std;

struct Trie
{
int ch[maxnode][maxs];
int val[maxnode];
int sz;
void clear(){sz=1;memset(ch[0],0,sizeof(ch[0]));}
int id(char c){return c-'a';}

void insert(const char *s,int v)
{
int u=0,n=strlen(s);
for(int i=0;i<n;i++)
{
int c=id(s[i]);
if(!ch[u][c])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=v;
}

void query(const char *s,int le
4000
n,vector<int>& ans)
{
int u=0;
for(int i=0;i<len;i++)
{
if(s[i]=='\0') break;
int c=id(s[i]);
if(!ch[u][c]) break;
u=ch[u][c];
if(val[u]!=0) ans.push_back(val[u]);
}
}
};

Trie tree;
char text[300000 + 10],word[100 + 10];
int f[300000 + 10],len[100 + 10],s;

int main()
{
int kase=1;
while(scanf("%s%d",text,&s)==2)
{
tree.clear();
for(int i=1;i<=s;i++)
{
scanf("%s",word);
len[i]=strlen(word);
tree.insert(word,i);
}
memset(f,0,sizeof(f));
int l=strlen(text);
f[l]=1;
for(int i=l-1;i>=0;i--)
{
vector<int> p;
tree.query(text+i,l-i,p);
for(int j=0;j<p.size();j++)
f[i]=(f[i]+f[i+len[p[j]]])%mod;
}
printf("Case %d: %d\n", kase++, f[0]);
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: