(Template) hdoj1251 (trie template title)

Topic link: https: //vjudge.net/problem/HDU-1251

Meaning of the questions: after a given number of strings, to give a series of fixed prefix, the number of query string to the string as a prefix for each prefix.

Ideas:

  I began to learn the dictionary tree today, starting with the entry title. To achieve an array, count array indicates the number of occurrences of each node, trie [0] as the root node.

AC code:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const  int MAXN = 1e6 + . 5 ;    // tree size, as far as possible up a bit 
int Trie [MAXN] [ 30 ], NUM [MAXN], CNT;
 char STR [ 15 ];

void insert(char *s){
    int len=strlen(s);
    int u=0;
    for(int i=0;i<len;++i){
        int t=s[i]-'a';
        if(!trie[u][t]){
            ++cnt;
            memset(trie[cnt],0,sizeof(trie[cnt]));
            trie[u][t]=cnt;
        }
        u=trie[u][t];
        ++num[u];
    }
}

int query(char *s){
    int len=strlen(s);
    int u=0;
    for(int i=0;i<len;++i){
        int t=s[i]-'a';
        if(!trie[u][t]) return 0;
        u=trie[u][t];
    }
    return num[u];
}

int main () {
    cnt=0;
    memset(trie[0],0,sizeof(trie[0]));
    memset(num,0,sizeof(num));
    while(gets(str),str[0]!='\0')
        insert(str);
    while(~scanf("%s",str))
        printf("%d\n",query(str));
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/FrankChen831X/p/11829364.html