hdu1251统计难题 字典树模板题(Trie树)

题面是给定若干个单词,然后再给出一些字符串,问你在之前所给的单词种,以某字符串为前缀的单词有多少个。

分析:很明显,是一道裸题,建字典树来做,顺便注意的是单词和字符串之间用空行做分隔,然后输入方式注意一下。

(吐槽一下,不知道为什么oj用G++交就MLE了,C++交就可以AC了)

下面我直接上代码:

#include <iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>

using namespace std;
struct node
{
    int cnt;
    node *next[26];

    void init()
    {
        cnt=0;
        for(int i=0; i<26; i++)
            next[i]=NULL;
    }
};

void Insert(node* root,char *s)
{
    node *p=root;
    for(int i=0; s[i]; i++)
    {
        int t=s[i]-'a';
        if(p->next[t]==NULL)
        {
            p->next[t]=new node;
            p=p->next[t];
            p->init();
        }
        else p=p->next[t];
        p->cnt++;
    }
}

int Find(node *root,char *s)
{
    node *p=root;
    for(int i=0; s[i]; i++)
    {
        int t=s[i]-'a';
        if(p->next[t])
            p=p->next[t];
        else return 0;
    }
    return p->cnt;

}


int main()
{
    char s[11];
    node *root=new node;
    root->init();
    while(gets(s)&&strlen(s))
    {
        Insert(root,s);
    }
    while(gets(s))
    {
        int ans=Find(root,s);
        cout<<ans<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/zero___zero/article/details/81041052
今日推荐