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

本文共 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://wxyql.baihongyu.com/

你可能感兴趣的文章
用SSG做IPsec***做成近似2层连接
查看>>
Spark Catalyst 的实现分析
查看>>
Windows Azure Pack与VMware VRA 对比(三)VRA角色简介及基础配置
查看>>
vue设置页面滚动
查看>>
HP刀片服务器系统Flex-10 VC配置与VMware vSphere网络设计
查看>>
《D3.js数据可视化实战手册》即将上市!
查看>>
用Nginx配置https加密站点
查看>>
Sersync数据同步
查看>>
hsrp+track
查看>>
Spring mvc 在一个定时器类里实现多个定时器任务
查看>>
Window下打开并读取文件的方法
查看>>
[讨论]UI层到底使用哪种类?
查看>>
使用JIRA搭建企业问题跟踪系统-1
查看>>
电脑族适合的花草茶
查看>>
saltstack知识点2
查看>>
Jenkins Pipeline
查看>>
ansible 模块之 yum模块详解
查看>>
PhoneGap跨平台Android环境的搭建
查看>>
西北大学(Northwestern University)-大数据分析课程
查看>>
php框架-hoby
查看>>