字典树 HDU1251

附上一篇博客http://blog.csdn.net/cambridgeacm/article/details/7752247

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

struct node
{
    int coun;
    node* child[26];
    node()
    {
        coun=0;
        for(int i=0;i<26;i++)
            child[i]=NULL;
    }
};

node* root=new node;
node* current;
node* newnode;

void inser(char* str)
{
    current=root;
    for(int i=0;i<strlen(str);i++)
    {
        int m=str[i]-'a';
        if(current->child[m]!=NULL)
        {
            current=current->child[m];
            (current->coun)++;
        }
        else
        {
            newnode=new node;
            current->child[m]=newnode;
            current=newnode;
            (current->coun)++;
        }
    }
}

int searc(char* str)
{
    current=root;
    for(int i=0;i<strlen(str);i++)
    {
        int m=str[i]-'a';
        if(current->child[m]!=NULL)
        {
            current=current->child[m];
        }
        else
            return 0;
    }
    return current->coun;
}

int main()
{
    char str[20];
    while(gets(str),strcmp(str,""))
        inser(str);
    while(scanf("%s",str)!=EOF)
        cout<<searc(str)<<endl;
    return 0;
}

 

posted @ 2016-05-25 09:05  相儒以沫  阅读(117)  评论(0编辑  收藏  举报