字典树模板题(la3942)

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 len,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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值