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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值