HDU 1251

来源:互联网 发布:奥卡姆剃刀知乎 编辑:程序博客网 时间:2024/06/01 08:32

思路: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;}


0 0