博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hdu 1247 Hat’s Words(字典树)
阅读量:6908 次
发布时间:2019-06-27

本文共 1703 字,大约阅读时间需要 5 分钟。

题目链接

分析:这道题可以使用stl中的map直接来解决,也可以使用字典树来解决,当然字典树的效率会更高

(1)stl解法不做过多的解释,这里有网上一个stl解法的链接 

(2)字典树解法, (详细看链接解释)

定义一个字典树结构体

typedef struct Trie{    bool flag;//从根到此是否为一个单词    Trie *next[MAXNUM];}Trie; 字典树的插入操作
void insert(char *word){    Trie *tem = root;    while(*word!='\0')    {        if(tem->next[*word-'a']==NULL)        {            Trie *cur = (Trie *)malloc(sizeof(Trie));            for(int i=0;i
next[i]=NULL; cur->flag=false; tem->next[*word-'a']=cur; } tem = tem->next[*word-'a']; word++; } tem->flag=true;}
以上两段代码是字典树的核心,要先弄懂。然后针对本题,flag是标志从根到当前位置是否可以组成一个单词,是为true,否为false。然后搜索每个单词是否有两个单词组成,这时就要把每个单词拆分,一个长度为n的单词可以拆分为n-1组组合,然后枚举判断是否在该字典树集合内。

 

#include 
#include
#include
#include
#define MAXNUM 26using namespace std;//单词char words[50005][100];//定义字典树typedef struct Trie{ bool flag;//从根到此是否为一个单词 Trie *next[MAXNUM];}Trie;Trie *root;void init(){ root = (Trie *)malloc(sizeof(Trie)); root->flag=false; for(int i=0;i
next[i]=NULL;}void insert(char *word){ Trie *tem = root; while(*word!='\0') { if(tem->next[*word-'a']==NULL) { Trie *cur = (Trie *)malloc(sizeof(Trie)); for(int i=0;i
next[i]=NULL; cur->flag=false; tem->next[*word-'a']=cur; } tem = tem->next[*word-'a']; word++; } tem->flag=true;}bool search(char *word){ Trie *tem = root; for(int i=0;word[i]!='\0';i++) { if(tem==NULL||tem->next[word[i]-'a']==NULL) return false; tem=tem->next[word[i]-'a']; } return tem->flag;}int main(){ init(); int t=0; char w[100]; while(scanf("%s",words[t])!=EOF) { insert(words[t]); t++; } for(int i=0;i

转载地址:http://fybcl.baihongyu.com/

你可能感兴趣的文章
casatwy组件化方案
查看>>
Linux中ls对文件进行按大小排序和按时间排序
查看>>
Unix/Linux下安装NPM
查看>>
Apache与Tomcat区别联系
查看>>
洪水***源码
查看>>
用shell编写批量打包日志脚本
查看>>
nginx访问白屏
查看>>
Pentaho6.1中D3可视化库的集成及数据联动的实现
查看>>
部署LyncServer2013之七 启动服务和登陆LyncServer控制面板
查看>>
Android开发者:你真的会用AsyncTask吗?
查看>>
马哥2016全新Linux+Python高端运维班第四周作业
查看>>
使用qemu工具创建虚拟机模板示例
查看>>
linux系统优化
查看>>
shell小技巧
查看>>
C++设计模式
查看>>
正则表达式(收藏版)
查看>>
zoom与scale的异同点
查看>>
十二周一课 LNMP架构介绍、 MySQL安装、PHP安装、 Nginx介绍
查看>>
ASA防火墙笔记及原理
查看>>
shell实例
查看>>