hdu_1251_统计难题_字典树

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1251

想象一下一个汉字后面可能接的数目,即使以10个数字作为基准,那花费的空间也是不敢想象的。

代码如下:

 

#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn=1000;
char str[100];
struct Node
{
    int count;//当前出现的次数
    struct Node* next[26];//共有26个英文字母
};
Node* root;
void insert(char* s)
{
    int i;
    int len=strlen(s);
    Node *current,*newset;
    if(len==0) return;
    current=root;
    for(i=0;i<len;i++)
    {
        if(current->next[s[i]-'a']!=NULL)
        {
            //current->count=current->count+1;
            current=current->next[s[i]-'a'];
            current->count=current->count+1; //有root的存在所以顺序才发生变化,因为current先从root变化到第一个字母,之后才是计数的变化
        }
        else
        {
            newset=(Node*)malloc(sizeof(Node));
            current->next[s[i]-'a']=newset;  //这一行写的时候有点犹豫,,
            for(int j=0;j<26;j++)
                newset->next[j]=NULL;
            current=newset;
            current->count=1;
        }
    }
}
int find(char*s)
{
    int i;
    int len=strlen(s);
    if(len==0) return 0;
    struct Node*current;
    current=root;
    for(i=0;i<len;i++)
    {
        if(current->next[s[i]-'a']!=NULL)
            current=current->next[s[i]-'a'];
        else return 0; //说明不存在

    }
    return current->count;
}
int main(void)
{
    int n,m;
    int i,j,k;

    root=(Node*)malloc(sizeof(Node)); //根节点初始化
    for(i=0;i<26;i++)
        root->next[i]=NULL; //忘了这一个,一直溢出
    while(gets(str)&&str[0]!='\0')
        insert(str);
    while(gets(str))
        cout<<find(str)<<endl;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值