HDU 1251

思路:Trie树,很早以前写过,但代码写的太屎,今天做别人比赛遇到了,就重写了一次。


#include<cstdio>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
class Node{
    public:
        int cnt;
        Node *child[26];
        Node(){
            cnt  =0;
            for(int i = 0;i < 26;i ++)
                child[i] = NULL;
        }
};
Node *root = new Node();
void Update(char *str){
    Node *tmp = root;
    while(*str != '\0'){
        if(tmp->child[*str - 'a'] == NULL){
            Node *p = new Node();
            tmp->child[*str - 'a'] = p;
        }
        tmp = tmp->child[*str - 'a'];
        tmp->cnt++;
        str++;
    }
}
int Getresult(char *str){
    Node *tmp = root;
    while(*str != '\0'){
        if(tmp->child[*str - 'a'] == NULL) return 0;
        tmp = tmp->child[*str - 'a'];
        str++;
    }
    return tmp->cnt;
}
int main(){
    char str[20];
    while(cin.getline(str,20) && strcmp(str,"")) Update(str);
    while(~scanf("%s",str)) printf("%d\n",Getresult(str));
    return 0;
}


posted on 2014-04-30 18:39  wangzhili  阅读(80)  评论(0编辑  收藏  举报