hdu 1251 통계 난제 (사전 단어를 정하고 어떤 단어를 접두사로 하는 단어의 개수를 조회합니다)

1385 단어 trie
코드:
#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;

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

Node *P_root;

void Insert(char s[])
{
    int len=strlen(s);
    Node *p=P_root;
    for(int i=0; i<len; i++)
    {
        int num=s[i]-'a';
        if(p->next[num]==NULL)
        {
            p->next[num]=(Node *)malloc(sizeof(Node));
            (*(p->next[num])).init();
        }
        p=p->next[num];
        p->cnt++;
    }
}

/*void Destroy(Node *p)
{
    for(int i=0;i<26;i++)
    {
        if(p->next[i]!=NULL)
        {
            Destroy(p->next[i]);
        }
    }
    free(p);
}*/

int Search(char s[])
{
    int len=strlen(s);
    Node *p=P_root;
    for(int i=0;i<len;i++)
    {
        int num=s[i]-'a';
        if(p->next[num]==NULL)
        {
            return 0;
        }
        p=p->next[num];
    }
    return p->cnt;
}

int main()
{
    P_root=(Node *)malloc(sizeof(Node));
    (*P_root).init();
    char s[15];
    while(gets(s)&&s[0]!=0)
        Insert(s);
    while(scanf("%s",s)!=EOF)
        printf("%d
",Search(s)); //Destroy(P_root); return 0; }

좋은 웹페이지 즐겨찾기