【题目链接】
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=22109
【解题报告】
trie树入门题目。我们知道给定字符串和给定的S个单词,求把这个字符串分解成若干个单词的方案数。
不难想到递推求解。
dp[i]表示text[i..LEN]这个字符串可以分解成若干个单词的方案数
dp[i]=sum( dp[i+len(x)] )(x表示一个可以作为i~LEN的前缀的单词)
初始化使dp[len]=1,表示如果字符串text[i..LEN]可以表示为一个单词时,方案数为1.
如何查找单词前缀?可以预处理单词,构造一颗trie树,保存的结点信息为单词长度,然后枚举字符串的数位i,遍历trie树查找即可。
【参考代码】
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int mod=20071027;
const int maxnode=4*1e5+10;
char text[300000+10];
int n;
int dp[300000+10];
vector<int>P;
struct TRIE{
int ch[maxnode][26];
int val[maxnode];
int sz;
void clear(){ sz=1; memset( ch,0,sizeof(ch) ); }
int idx( char c){ return c-'a'; }
void insert( char* s, int v )
{
int L=strlen(s),u=0;
for( int i=0; i<L; i++ )
{
int c=idx(s[i]);
if( !ch[u][c] )
{
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=v;
}
void find_pre( const char* S )
{
int L=strlen(S),u=0;
for( int i=0; i<L; i++ )
{
if(S[i]=='\0')break;
int c=idx(S[i]);
if(!ch[u][c])break;
if(val[ch[u][c]] )P.push_back(val[ch[u][c]]);
u=ch[u][c];
}
}
}trie;
int main()
{
int kase=0;
while(~scanf("%s",text))
{
scanf("%d",&n);
trie.clear();
memset( dp,0,sizeof(dp) );
for( int i=1; i<=n;i++ )
{
char word[100+10];
scanf("%s",word);
int v=strlen(word);
trie.insert( word, v );
}
int L=strlen(text);
dp[L]=1;
for( int i=L-1; i>=0; i-- )
{
P.clear();
trie.find_pre( text+i );
for( int j=0; j<P.size(); j++ )
{
dp[i]=(dp[i]+dp[i+P[j]])%mod;
}
}
printf("Case %d: %d\n",++kase,dp[0]);
}
return 0;
}