UVA1401 (字典树加简单dp)

#pragma GCC optimize(2)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 5e5+10;
const int mod=20071027;
const int sigma_size=26;
int dp[N];
char str[N];
char s[105];
struct Trie{
    int ch[N][sigma_size];
    int val[N];
    int sz;
    Trie(){sz=1;memset(ch[0],0,sizeof(ch[0]));}
    int idx(char c) {return c-'a';}
    void reset(){memset(ch,0,sizeof(ch));memset(val,0,sizeof(val));sz=1;}
    void insert(char *s,int v)
    {
        int u=0,n=strlen(s);
        for(int i=0;i<n;i++)
        {
            int c=idx(s[i]);
            if(!ch[u][c])
            {
                memset(ch[sz],0,sizeof(ch[sz]));
                val[sz]=0;
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]=v;
    }
    int query(char *s,int a)
    {
        int u=0,res=0;
        for(int i=a;s[i];++i)
        {
            int c=idx(s[i]);
            if(!ch[u][c])
                return res;
            u=ch[u][c];
            if(val[u])
            {
                res+=dp[i+1];
                res%=mod;
            }
        }
        return res;
    }
};
Trie T;
int main()
{
    int kase=0;
    while(scanf("%s",str)!=EOF)
    {
        int n,m=strlen(str);
        scanf("%d",&n);
        T.reset();
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            scanf("%s",s);
            T.insert(s,1);
        }
        dp[m]=1;
        for(int i=m-1;i>=0;i--)
        {
            dp[i]=T.query(str,i);
        }
        printf("Case %d: %d\n",++kase,dp[0]);
    }
    return 0;
}

 

posted @ 2019-10-16 12:46  hh13579  阅读(139)  评论(0编辑  收藏  举报