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

UVA-1401-Remember the Word(Trie)

时间:2014-05-10 03:48:22      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   tar   

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 , 1bubuko.com,布布扣Sbubuko.com,布布扣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


思路:dp[i]表示从第i个字符开始到字符串尾的组合情况的方案数,从后往前推即可。


#include <stdio.h>
#include <string.h>

int son[400001][26],val[400001],dp[400001],cnt;

char s[300001],ts[101];

void insert(char *str)
{
    int u=0,i,j,id;

    for(i=0;str[i];i++)
    {
        id=str[i]-‘a‘;

        if(!son[u][id])
        {
            for(j=0;j<26;j++) son[cnt][j]=0;

            val[cnt]=0;

            son[u][id]=cnt++;
        }

        u=son[u][id];
    }

    val[u]++;
}

int main()
{
    int n,i,j,u,id,casenum=1;

    while(~scanf("%s",s))
    {
        for(i=0;i<26;i++) son[0][i]=0;
        cnt=1;

        scanf("%d",&n);

        while(n--)
        {
            scanf("%s",ts);

            insert(ts);
        }

        n=strlen(s);

        dp[n]=1;

        for(i=n-1;i>=0;i--)
        {
            u=0;
            j=i;
            id=s[j]-‘a‘;

            dp[i]=0;

            while(u=son[u][id])//如果可以继续走下去就继续走
            {
                dp[i]+=val[u]%20071027*dp[j+1]%20071027;

                j++;

                if(j<n) id=s[j]-‘a‘;
                else break;
            }
        }

        printf("Case %d: %d\n",casenum++,dp[0]%20071027);
    }

}


UVA-1401-Remember the Word(Trie),布布扣,bubuko.com

UVA-1401-Remember the Word(Trie)

标签:des   style   blog   class   code   tar   

原文地址:http://blog.csdn.net/faithdmc/article/details/25424553

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