uva1401 Remember the Word

137 篇文章 0 订阅
78 篇文章 0 订阅

Neal is very curious about combinatorial problems, and now here comes
a problem about words. Know- 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 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 le contains multiple test cases. For each test case: the rst
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 le. Output For each test case, output the number, as
described above, from the task description modulo 20071027.

用dp[i]表示i..l的字符串的分解方法数,dp[i]=sum{dp[j+1]}(i<=j<=l,i..j是单词)。
如果直接暴力计算,复杂度O(l^2 * n * lenw)无法承受。
因为当j向后循环时,相当于不断加入字符,所以可以用trie树维护,先把所有单词加入trie树中,然后随着j向下寻找。

#include<cstdio>
#include<cstring>
const int mod=20071027;
char a[300010],s[4010][110];
int dp[300010],son[400010][30],tot,n,l,len[4010];
bool have[400010];
void init()
{
    int i,j,p;
    l=strlen(a+1);
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        scanf("%s",s[i]+1);
        len[i]=strlen(s[i]+1);
    }
    memset(son,0,sizeof(son));
    memset(have,0,sizeof(have));
    tot=0;
    for (i=1;i<=n;i++)
    {
        p=0;
        for (j=1;j<=len[i];j++)
        {
            if (!son[p][s[i][j]-'a']) son[p][s[i][j]-'a']=++tot;
            p=son[p][s[i][j]-'a'];
        }
        have[p]=1;
    }
}
void solve()
{
    int i,j,p;
    memset(dp,0,sizeof(dp));
    dp[l+1]=1;
    for (i=l;i;i--)
    {
        p=0;
        for (j=i;j<=l;j++)
        {
            p=son[p][a[j]-'a'];
            if (!p) break;
            if (have[p]) dp[i]=(dp[i]+dp[j+1])%mod;
        }
    }
}
int main()
{
    int K=0;
    while (scanf("%s",a+1)==1)
    {
        init();
        solve();
        printf("Case %d: %d\n",++K,dp[1]);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值