L Language

https://loj.ac/problem/10053

Title Description

  And a sentence given a dictionary, to find a maximum of several positions can be understood that this phrase (prefix).

Thinking

  Dictionary tree, nature as its name suggests, the dictionary can be used to deal with the problem. First, obviously we can build a dictionary tree, then we are clear that we seek to understand the prefix, not the total length, not multi-string matching, without AC automaton. Because of dictionary words may be nesting, we consider f [i] indicates whether we can match to this one, so we can start from every place can match the string matching, and then record the answers. The biggest i satisfying f [i] = 1 is the answer.

Code

#include <bits/stdc++.h>
using namespace std;
int ch[1000005][30],tot;
char s[30],ss[1000005];
bool ed[1000005],f[1000005];
void insert(char *s)
{
    int u=1,len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int c=s[i]-'a';
        if(!ch[u][c])ch[u][c]=++tot;
        u=ch[u][c];
    }
    ed[u]=1;
}
int find(char *s)
{
    int u=1,len=strlen(s+1);
    int ans=0;
    memset(f,0,sizeof(f));
    f[0]=1;
    for(int i=0;i<=len;i++)
    {
        if(!f[i])continue ;
        else ans=i;
        u=1;
        for(int j=i+1;j<=len;j++)
        {
//            cout<<j<<' '<<s[j]<<endl;
            int c=s[j]-'a';
            if(!ch[u][c])break ;
            u=ch[u][c];
            if(ed[u])f[j]=1;
        }
    }
    return ans;
}
int main() 
{
    int n,m;
    scanf("%d%d",&n,&m);
    tot=1;
    for(int i=1;i<=n;i++)
    {
        scanf(" %s",s);
        insert(s);
    }
    for(int i=1;i<=m;i++)
    {
        scanf(" %s",ss+1);
        printf("%d\n",find(ss));
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/fangbozhen/p/11628563.html