Prefix Statistics

Topic links: https://www.acwing.com/problem/content/144/

The meaning of problems: given N strings S . 1 , S 2 ... S N Sl, S2 ... the SN, the next inquiry M times, each time a given query string T, find S . 1 Sl ~ S N the SN has how many string is a prefix of T.

Thinking: this can be inserted into a string of N Trie trie, an integer ans stored on each node in the Trie, recording the node is the node number at the end of the string. For each inquiry, in Trie

          cnt value of each node of the tree to retrieve T, cumulative way during the retrieval process, is the answer to the inquiry

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int trie[1000010][30],b[1000010];
int tot=1;
char a[1000010];
void insert(char a[])
{
    int n=strlen(a);
    int p=1;
    for(int i=0;i<n;i++)
    {
        int w=a[i]-'a';
        if(trie[p][w]==0)
            trie[p][w]=++tot;
        p=trie[p][w];
    }
    b[p]++;
    return;
}
int fun(char a[])
{
    int n=strlen(a);
    int sum=0,p=1;
    for(int i=0;i<n;i++)
    {
        int w=a[i]-'a';
        if(trie[p][w]==0)
            break;
        p=trie[p][w];
        sum+=b[p];
    }
    return sum;
}
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i=0; i<n; i++)
    {
        scanf("%s",a);
        insert(a);
    }
    for(int i=0;i<m;i++)
    {
        scanf("%s",a);
        int sum=fun(a);
        printf("%d\n",sum);
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/zcb123456789/p/11299875.html