HDU1251:统计难题

这道题是很简单的字典树的题,很基础,直接套模板就行。

字典树的讲解见:http://blog.csdn.net/u010142538/article/details/9729601

code:

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <iomanip>
#include <map>
#include <climits>
#include <set>
#include <vector>
using namespace std;
typedef struct Trie
{
    int v ;
    Trie *next[26] ;
};
Trie root ;
void createTrie(char *str)
{
    int l = strlen(str) ;
    Trie *p = &root , *q ;
    for(int i = 0 ; i < l ; i ++)
    {
        int m = str[i] - 'a' ;
        if(p -> next[m] == NULL)
        {
            q = (Trie *)malloc(sizeof(root)) ;
            q -> v = 1 ;
            for(int j = 0 ; j < 26 ; j ++)
                q -> next[j] = NULL ;
            p -> next[m] = q ;
            p = p -> next[m] ;
        }
        else
        {
            p -> next[m] -> v ++ ;
            p = p -> next[m] ;
        }
    }
}
int findTrie(char *str)
{
    int l = strlen(str) ;
    Trie *p = &root ;
    for(int i = 0 ; i < l ; i ++)
    {
        int m = str[i] - 'a' ;
        p = p -> next[m] ;
        if(p == NULL)
            return 0 ;
    }
    return p -> v ;
}
int main()
{
    char tmp[15] ;
    //root = (Trie *)malloc(sizeof(root)) ;
    for(int i = 0 ; i < 26 ; i ++)
        root.next[i] = NULL ;
    while(gets(tmp) && tmp[0] != '\0')
    {
        createTrie(tmp) ;
    }
    memset(tmp , 0 , sizeof(tmp)) ;
    while(scanf("%s" , tmp) != EOF)
    {
        int ans = findTrie(tmp) ;
        printf("%d\n" , ans) ;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值