UVA 1401 Remember the Word

1401 - Remember the Word

Time limit: 3.000 seconds

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 ≤ S ≤ 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


【题目分析】

    首先很容易想到动态规划的状态转移方程,很简单的满背包问题。但是每次判断子串十分麻烦,肯定会超时。但是如果把所有的字符串插入到trie树当中去,每一个位置最多只需要查询100次即可出解。


【代码】

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#define F(i,j,k) for (int i=j;i<=k;++i)
#define M0(a) memset(a,0,sizeof a)
#define M1(a) msmset(a,-1,sizeof a)
#define D(i,j,k) for (int i=j;i>=k;--i)
#define ML 300001
#define MP 400001
#define MOD 20071027
using namespace std;
int x,trie[MP][26],tot=1,v[MP],dp[MP],t=0;
char s[ML],ss[101];
void insert()
{
	scanf("%s",ss);
	int now=1,l=strlen(ss);
	F (i,0,l-1){
		if (!trie[now][ss[i]-'a']) trie[now][ss[i]-'a']=++tot;
		now=trie[now][ss[i]-'a'];
	}
	v[now]++;
}
void dpp()
{
	int len=strlen(s)-1;
	dp[len+1]=1;
	for (int i=len;i>=0;--i){
		int now=1;
		int j=i;
		while(j<=len){
			if (trie[now][s[j]-'a']!=0)
			{
				now=trie[now][s[j]-'a'];
				if (v[now]){
					dp[i]+=dp[j+1];
					dp[i]%=MOD;
				}
				++j;
			}
			else break;
		}
	}
}
int main()
{
	while (scanf("%s",s)==1){
		M0(trie);
		M0(v);
		M0(dp);
		tot=1;
		scanf("%d",&x);
		F(i,1,x)insert();
		dpp();
		printf("Case %d: %d\n",++t,dp[0]);
	}
} 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值