hdu1251(字符串Trie)

Trie基础题

 

数组写法:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e6 + 10;
int trie[maxn][28], num[maxn];
//bool tail[maxn][28];
int sz;

void init()
{
    sz = 1;
    memset(trie[0], 0, sizeof(trie[0]));        //手误,原来sizeof(trie)了......
}


int idx(char ch)
{
    return ch - 'a';
}


void insert(char *s)
{
    int u = 0, len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(!trie[u][t])
        {
            memset(trie[sz], 0, sizeof(trie[sz]));
            trie[u][t] = sz++;
        }
        u = trie[u][t];
        num[u]++;
    }
}


int query(char *s)
{
    int u = 0, len = strlen(s);
    int sum = 0;

    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(!trie[u][t])   return 0;
        u = trie[u][t];
    }
    sum = num[u];
    return sum;
}



int main()
{
    char word[15];
    init();
    while(gets(word) && word[0] != NULL)            //此题巩固了gets用法:不保存'\n',将其转换为'\0'(NULL),而且另一题中在gets前如有回车需要加getchar()!不然会多出一行空行
    {
        insert(word);
    }

    while(scanf("%s", word) == 1)
    {
        int ans = query(word);
        printf("%d\n", ans);
    }
    return 0;
}

链表版本:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 3e3 + 10;
const int sz = 28;

struct trie
{
    int num;
    bool tail;
    struct trie *next[sz];
};

trie *root;

trie *init()
{
    trie *p = (trie*)malloc(sizeof(trie));
    p->num = 0;
    p->tail = 0;
    for(int i = 0; i < sz; i++)
        p->next[i] = NULL;

    return p;
}


int idx(char ch)
{
    return ch - 'a';
}


void insert(char *s)
{
    trie *p = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(p->next[t] == NULL)
        {
            p->next[t] = init();
        }
        p = p->next[t];
        p->num++;
    }
    p->tail = 1;
}


int query(char *s)
{
    trie *p = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int t = idx(s[i]);
        if(p->next[t] == NULL)  return 0;
        p = p->next[t];
    }
    return p->num;
}

void del(trie *p)
{
    for(int i = 0; i < sz; i++)
    {
        if(p->next[i])
            del(p->next[i]);
    }
    del(p);
}



int main()
{
    char word[15];
    root = init();
    while(gets(word) && word[0] != NULL)            //
    {
        insert(word);
    }

    while(scanf("%s", word) == 1)
    {
        int ans = query(word);
        printf("%d\n", ans);
    }
    del(root);
    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值