hdu-1251

思路:

Trie树模板的小变形,在模板中有一个思维拓展的点要值得我们注意,就是每一个节点的e值,在本题中他们不再用来标记单词的结尾,而是用来计数,因为对于Trie树的某一个确定的位置,一个给定的单词只能走过一遍,因此这样记录可以确定一个位置被多少个单词给“经过”,然后找前缀的时候只要遍历到的最后一个字母所在的位置,输出他的count即可。

 

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

struct node
{
    int e;
    struct node* next[26];
    node()
    {
        e = 0;
        for(int i = 0;i <= 25;i++)
            next[i] = NULL;
    }
};
node* root;
char str[100007][17];
char cs[100007][17];

void Insert(char* s)
{
    node* p = root;
    for(;*s != '\0';s++)
    {
        int n = *s-'a';
        if(p->next[n] == NULL)
            p->next[n] = new node();
        p = p->next[n];
        p->e++;
    }
}

int find(char* s)
{
    node* p = root;
    for(;*s!='\0';s++)
    {
        int n = *s-'a';
        if(p->next[n] == NULL) return 0;
        p = p->next[n];
    }
    return p->e;
}

int main()
{
    int i,j;
    i = 0;
    j = 0;
    root = new node();
    while(gets(str[i]),strcmp(str[i],""))
        Insert(str[i++]);
    while(scanf("%s",cs[j]) != EOF)
        cout<<find(cs[j++])<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/immortal-worm/p/5197133.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值