hdu 1251(字典树) 统计难题

点击打开链接


解题思路:直接套用字典树的模板,注意以空行结束的判断是 strcmp(str,"")==0


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
//创建一个字典树结构体
struct Trie{
    int num;
    Trie *child[26];

     //放在结构体里面初始化

    Trie(){
        num = 0;
        memset(child , 0 , sizeof(child));
    }
};
Trie *root;
//插入字母建立树
void Tree_Insert(char *str){
    Trie *s = root;
    int i = 0;
    int len = strlen(str) - 1;
    while(str[i]){
        int id = str[i] - 'a';
        if(s -> child[id] == NULL)
            s -> child[id] = new Trie();//建立中间的节点
        s = s -> child[id];
        s ->num++;

        i++;

      }
}
//查找
int Tree_search(char *str){
    Trie *s = root;
    int count;
    while(str[i]){
        int id = str[i] - 'a';
        if(s -> child[id] == 0){
            return 0;
        }
        else{
            s = s -> child[id];
            count = s -> num;
        }

        i++;

     }
    return count;
}
int main(){
    root = new Trie();//创建并且初始化
    char str[15];
    while(gets(str),strcmp(str,"")){ //注意这里的判断条件,逗号表达式
        Tree_Insert(str);
    }
    while(gets(str)){
        cout<<Tree_search(str)<<endl;
    }
    return 0;
}





你可能感兴趣的:(HDU)