HDU-1251 trie树

本文介绍了一道经典的字符串匹配问题,并通过使用Trie树的数据结构进行高效求解。针对题目要求,文章给出了详细的Trie树构建与查询过程,包括插入字符串到Trie树中和查询字符串是否为树中某个节点的前缀。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


题意:先给出一堆字符串,然后又给出一堆字符串,问第二堆每个字符串是第一堆字符串中多少个字符串的前缀。


题解:trie树模板题。


代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct trie{
    trie *Next[30];
    int v;
};
void create_tree(char s[],trie *q)
{
    int n = strlen(s);
    //cout << "n: " << n <<endl;
    trie *p;
    for(int i=0;i<n;i++){
        int id = s[i] - 'a' + 1;
        //cout << "id,v : " << id << ' ' << q -> v << endl;
        if(q -> Next[id] == NULL){
            p = new trie;
            for(int i=0;i<30;i++)
                p -> Next[i] = NULL;
            p -> v = 1;
            q -> Next[id] = p;
        }
        else (q -> Next[id] -> v)++;
        q = q -> Next[id];
    }
}
int query_tree(char s[],trie *p)
{
    int n = strlen(s);
    for(int i=0;i<n;i++){
        int id = s[i] - 'a'+1;
        if(p -> Next[id] != NULL){
            //cout << "id,v : " << id << ' ' << p-> Next[id]-> v << endl;
            if(i == n-1) return p -> Next[id] -> v;
            p = p -> Next[id];
        }
        else return 0;
    }
    return 0;
}
void del_tree(trie *p)
{
    for(int i=0;i<30;i++){
        if(p -> Next[i] != NULL)
            del_tree(p -> Next[i]);
    }
    delete p;
}
int main()
{
    char x;
    char temp[15];
    trie *root;
    root = new trie;
    for(int i=0;i<30;i++)
        root -> Next[i] = NULL;
    root -> v = 0;
    int cnt = 0;
    for(;;){
        x = getchar();
        if(x != '\n')
            temp[cnt++] = x;
        else{
            if(cnt == 0)
                break;
            temp[cnt] = 0;
//cout << " tmep:" <<temp <<endl;
            create_tree(temp,root);
            cnt = 0;
        }
    }
    while(scanf("%s",temp) != EOF){
       // cout << "temp : " << temp <<endl;
        int cnt = query_tree(temp,root);
        printf("%d\n",cnt);
    }
    del_tree(root);

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值