HDU 1251 统计难题 (字典树模板题)

题意:给你一堆单词,现在有多次询问,每次询问求以给定字符串作为前缀的单词有多少个。

Sample Input
banana
band
bee
absolute
acm


ba
b
band
abc


Sample Output
2
3
1
0

有两种建树方法,一种动态一种静态。

一般来说静态更好一些。

动态代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 105;
char str[maxn];
struct node
{
    int cnt;//根据需要变化,这里是记录有该前缀的数量
    struct node *next[26];
    //next是表示每层有多少种类的数,如果只是小写字母,则26即可,
	//若改为大小写字母,则是52,若再加上数字,则是62了
    node()
    {
        cnt = 0;
        memset(next, 0, sizeof(next));
    }
};

node *root = NULL;

void buildTrie(char *s)
{
    node *p = root;
    node *tmp = NULL;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(p->next[s[i]-'a'] == NULL)   //该前缀没出现过
        {
            tmp = new node;
            p->next[s[i]-'a'] = tmp;
        }
        p = p->next[s[i]-'a'];
        p->cnt++;
    }
}

int findTrie(char *s)
{
    node *p = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(p->next[s[i]-'a'] == NULL)   //不存在以该字符串为前缀
            return 0;
        p = p->next[s[i]-'a'];
    }
    return p->cnt;
}

void deleateTrie(node *cur)//动态字典树,有时会超内存, 这时就要记得释放空间了
{
    for(int i = 0; i < 26; i++)
        if(cur->next[i])
            deleateTrie(cur->next[i]);
    delete cur;
}

int main(void)
{
    root = new node;
    while(gets(str))
    {
        if(!strlen(str)) break;
        buildTrie(str);
    }
    while(gets(str) != NULL)
        printf("%d\n", findTrie(str));
    return 0;
}


静态代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxnode = 1e6+5;
const int maxn = 27;
int sz, ch[maxnode][maxn], val[maxnode];
char str[15];

void init()
{
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
}

void Insert(char *s)
{
    int u = 0;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(ch[u][s[i]-'a'] == 0)
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][s[i]-'a'] = sz++;
        }
        u = ch[u][s[i]-'a'];
        val[u]++;
    }
}

int Match(char *s)
{
    int u = 0;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(ch[u][s[i]-'a'] == 0)
            return 0;
        u = ch[u][s[i]-'a'];
    }
    return val[u];
}

int main(void)
{
    init();
    while(gets(str))
    {
        if(!strlen(str)) break;
        Insert(str);
    }
    while(gets(str) != NULL)
        printf("%d\n", Match(str));
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值