HDU 3530 Hat’s Words(字典树)

题目链接: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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值