程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA-1401-Remember the Word(Trie)

UVA-1401-Remember the Word(Trie)

編輯:C++入門知識

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$ \le$S$ \le$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 
#include 

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved