现在的位置: 首页 > 综合 > 正文

LA3942 Trie+DP

2019年08月21日 ⁄ 综合 ⁄ 共 1303字 ⁄ 字号 评论关闭

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

详解大白书 P209

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 500000
const int mod=20071027;
struct node
{
    int ch[27];
    int v; // 0表示不是单词,其余数字表示为一个单词。
    node()
    {
        memset(ch,0,sizeof(ch));
        v=0; 
    }
}tree[MAXN];
int tot;
char op[300010];
char word[100];
int d[300010];
void insert(int v)
{
    int len=strlen(word);
    int root=0;
    for(int i=0;i<len;i++)
    {
        if(tree[root].ch[word[i]-'a']==0) tree[root].ch[word[i]-'a']=tot++;
        root=tree[root].ch[word[i]-'a'] ;
    }
    tree[root].v=v;
}
void cheak(int i,int len)
{
    int ans=0;
    int root=0;
    for(int j=i;j<=len;j++)
    {
        if(tree[root].ch[op[j]-'a']==0) break;
        root=tree[root].ch[op[j]-'a'];
        if(tree[root].v) ans+=d[j+1]%mod;
        ans%=mod;
    }
    d[i]=ans;
}
int main()
{
    int kase=1;
    while(~scanf("%s",op))
    {
        memset(tree,0,sizeof(tree));
        int len=strlen(op);
        tot=1;
        int s;
        scanf("%d",&s);
        for(int i=1;i<=s;i++)
        {
            scanf("%s",word);
            insert(i);
        }
        memset(d,0,sizeof(d));
        d[len]=1; // 初始化边界
        for(int i=len-1;i>=0;i--)
        {
            cheak(i,len-1);
        }
        printf("Case %d: %d\n",kase++,d[0]%mod);
    }

}
/**
abcd
4
a
b
cd
ab
abcd
0
**/

抱歉!评论已关闭.