HDU 3530 Hat’s Words(字典树)

本文介绍了一种利用字典树解决字符串匹配问题的方法。通过离线接收所有字符串并建立字典树,再进行查询判断是否满足特定条件,最终输出符合条件的字符串。文章提供了完整的C++代码实现。

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

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3530

字典树,先离线接收所有串并建立字典树,然后再查询,每次查询到前面部分是单词再查询后面是不是单词,满足条件输出!


#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define maxn 100000
struct trie{
    trie *next[26];
    bool is_word;
}po[maxn];
int pos=1;
char word[51000][20];
int insert_trie(trie *root,char *name){
    if(name[0]==0){
        root->is_word=true;return 0;
    }
    int ch=name[0]-'a';
    if(root->next[ch])
    insert_trie(root->next[ch],name+1);
    else{
        root->next[ch]=&po[pos++];
        insert_trie(root->next[ch],name+1);
    }
    return 0;
}
bool query(trie *root,char *name){
    if(name[0]==0){
        return root->is_word;
    }
    if(root->next[name[0]-'a']==NULL)
    return false;
    return query(root->next[name[0]-'a'],name+1);
}
bool find_ans(trie *root,char *name){
    if(name[0]==0) return false;
    if(root->is_word){
        if(query(&po[0],name)) return true;
    }
    return find_ans(root->next[name[0]-'a'],name+1);
}
int main(){
    int i=0,j,k;
    while(scanf("%s",word[i])!=EOF)insert_trie(&po[0],word[i++]);
    for(j=0;j<i;j++){
        if(find_ans(&po[0],word[j])) printf("%s\n",word[j]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值