HDU 1251 统计难题


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX_SIZE 26


struct TrieNode {
    int char_count;
    TrieNode* son_char[MAX_SIZE];
};


void clear_node( TrieNode* node ) {
    node->char_count = 0;
    for ( int i = 0; i < MAX_SIZE; ++i ) {
        node->son_char[i] = NULL;
    }
}


void insert_string( TrieNode* root, char* str ) {

    const int str_len  = strlen( str );
    TrieNode* now_node = root;

    for ( int i = 0; i < str_len; ++i ) {
        const char ch = str[i] - 'a';
        if ( now_node->son_char[ch] == NULL ) {
            TrieNode* temp = ( TrieNode* )malloc( sizeof( TrieNode ) );
            clear_node( temp );
            now_node->son_char[ch] = temp;
        }
        now_node = now_node->son_char[ch];
        now_node->char_count += 1;
    }

}


int search_string( TrieNode* root, char* str ) {

    TrieNode* now_node = root;
    const int str_len = strlen( str );

    for ( int i = 0; i < str_len; ++i ) {
        const char ch = str[i] - 'a';
        now_node = now_node->son_char[ch];
        if ( now_node == NULL )
            return 0;
    }

    return now_node->char_count;

}


void delete_node( TrieNode* node ) {
    for ( int i = 0; i < MAX_SIZE; ++i ) {
        if ( node->son_char[i] != NULL )
            delete_node( node->son_char[i] );
    }
    free( node );
}


int main() {

    TrieNode* root = ( TrieNode* )malloc( sizeof( TrieNode ) );
    clear_node( root );
    char str[11];
    while ( gets( str ) && str[0] != '\0' ) {
        insert_string( root, str );
    }

    while ( gets( str ) ) {
        int res = search_string( root, str );
        cout << res << endl;
    }

    delete_node( root );

    return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值