La3942 remember the word (trie + dp)

Source: Internet
Author: User

Simple application of the trie graph. The key to this question is to come up with a recursive formula. D (I) indicates the string starting with character I, d (I) = sum {d (I + Len (x)}, X is s [I... l] prefix. Then, all words that can be broken down into a trie tree and then run the parent string on it. D [0] is the total number of solutions.

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#define mod 20071027#define M 400005using namespace std;int n,top,len;int tree[M][27];char S[M];char p[105];int val[M];int d[M];void init(){    top=1;    memset(tree,0,sizeof(tree));    memset(d,0,sizeof(d));}int idx(char c){    return c-'a';}void insert(char *s){    int Len=strlen(s);    int u=0;    for(int i=0;i<Len;i++)    {        int c=idx(s[i]);        if(!tree[u][c])        {            val[top]=0;            tree[u][c]=top++;        }        u=tree[u][c];    }    val[u]=1;}int query(char *s,int start){    int count=0;    int u=0;    for(int i=start;i<len;i++)    {        int c=idx(s[i]);        u=tree[u][c];        if(!u) return count;        if(val[u])        {            count+=d[i+1];            count%=mod;        }    }    return count;}int main(){    int t=1;    //freopen("d:\\test.txt","r",stdin);    while(scanf("%s",S)!=EOF)    {        scanf("%d",&n);        init();        for(int i=0;i<n;i++)        {            scanf("%s",p);            insert(p);        }        len=strlen(S);        d[len]=1;        for(int i=1;i<=len;i++)        {            d[len-i]=query(S,len-i);        }        cout<<"Case "<<t++<<": "<<d[0]<<endl;    }    return 0;}


La3942 remember the word (trie + dp)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.