码迷,mamicode.com
首页 > 其他好文 > 详细

LA3942 Remember the Word(字典树+记忆化搜索)

时间:2015-08-03 21:03:32      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:记忆化搜索   字典树   

题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=22109

题意:给出一个由S个不同单词组成的字典和一个长字符串。把这个字符串分解成若干个单词的连接(单词可以重复使用),由多少种方法?比如,有4个单词a,b,cd,ab,则abcd有两种分解方法:a+b+cd和ab+cd

分析:首先将输入的字典建成字典树。然后记忆化搜索~

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 4e5+6;
const int mod =20071027;

int dp[maxn]; 
int son[maxn][26],cur,Len;
int end[maxn];
char ss[maxn],st[maxn];
int newnode()
{
	end[cur]=0;
	fill(son[cur],son[cur]+26,-1); 
	return cur++;
}
void Clear()
{
	cur=0;
	newnode();
}
void Insert(char str[])
{
	int len=strlen(str),index,i,root=0;
	for(i=0;i<len;i++)
	{
		index=str[i]-'a';
		if(son[root][index]==-1)
			son[root][index]=newnode();
		root=son[root][index];
	}
	end[root]++;
}

int Query(int start)
{
	if(start>=Len)
		return 1;
	if(dp[start]!=-1)
		return dp[start];
	int ret(0),index,i,root=0;
	for(i=start;i<Len;i++)
	{
		index=ss[i]-'a';
		if(son[root][index]!=-1 && end[son[root][index]])
			ret+=Query(i+1)%mod;
		if(son[root][index]==-1)
			return dp[start]=ret%mod;
		root=son[root][index];
	}
	return dp[start]=ret%mod;
}

int main()
{
	int ncase=1,n;
	while(scanf("%s%d",ss,&n)!=EOF)
	{
		Clear();
		Len=strlen(ss);
		fill(dp,dp+Len+1,-1);
		while(n--)
		{
			scanf("%s",st); 
			Insert(st);
		}
		printf("Case %d: %d\n",ncase++,Query(0));
	}
	return 0;
}

LA3942 Remember the Word(字典树+记忆化搜索)

标签:记忆化搜索   字典树   

原文地址:http://blog.csdn.net/w20810/article/details/47260923

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!