hdu1251(Trie)

题目链接

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e6 + 10;
int trie[maxn][28], num[maxn];
//bool tail[maxn][28];
int sz;

void init()
{
    sz = 1;
    memset(trie[0], 0, sizeof(trie[0]));
}


int idx(char ch)
{
    return ch - 'a';
}


void insert(char *s)
{
    int u = 0, len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(!trie[u][t])
        {
            memset(trie[sz], 0, sizeof(trie[sz]));
            trie[u][t] = sz++;
        }
        u = trie[u][t];
        num[u]++;            //在当前字符的下一层再累加
    }
}


int query(char *s)
{
    int u = 0, len = strlen(s);
    int sum = 0;

    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(!trie[u][t])   return 0;
        u = trie[u][t];
    }
    sum = num[u];
    return sum;
}



int main()
{
    char word[15];
    init();
    while(gets(word) && word[0] != NULL)            //gets : '\n' -> '\0'
    {
        insert(word);
    }

    while(scanf("%s", word) == 1)
    {
        int ans = query(word);
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38577732/article/details/89518257
今日推荐