前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >hdu--(1247)Hat’s Words(trie树)

hdu--(1247)Hat’s Words(trie树)

作者头像
Gxjun
发布2018-03-26 11:36:52
4460
发布2018-03-26 11:36:52
举报
文章被收录于专栏:mlml

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 8343    Accepted Submission(s): 3004

Problem Description

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary. You are to find all the hat’s words in a dictionary.

Input

Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words. Only one case.

Output

Your output should contain all the hat’s words, one per line, in alphabetical order.

Sample Input

a ahat hat hatword hziee word

Sample Output

ahat

hatword

Author

戴帽子的

简述题意: 给你很多单词,查找能够由其中的两个单词拼合而成的单词,并按字典序输出.....

代码:

代码语言:javascript
复制
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<cstdlib>
 4 typedef struct node
 5 {
 6   struct node *child[26];
 7   bool tail;
 8 }Trie;
 9 char mat[50005][15];
10 void Insert(char *s,Trie *root)
11 {
12     int i,pos,j;
13     Trie *cur=root,*curnew;
14     for(i=0;s[i]!='\0';i++){
15         pos=s[i]-'a';
16          if(cur->child[pos]==NULL)
17          {
18              curnew=(Trie *)malloc(sizeof(Trie));
19              for(j=0;j<26;j++)
20              curnew->child[j]=NULL;
21              curnew->tail=false;
22              cur->child[pos]=curnew;
23          }
24          cur=cur->child[pos];
25     }
26      cur->tail=true;
27 }
28 bool check(char *s,Trie *root)
29 {
30     int i,pos;
31     Trie *cur=root;
32    for(i=0;s[i]!='\0';i++)
33    {
34      pos=s[i]-'a';
35      if(cur->child[pos]==NULL) return 0;
36       cur=cur->child[pos];
37    }
38    if(cur->tail==1)return 1;
39    return 0;
40 }
41 bool query(char *s,Trie *root)
42 {
43     int i,pos;
44     Trie *cur=root;
45     for(i=0;s[i]!='\0';i++)
46     {
47         pos=s[i]-'a';
48         if(cur->child[pos]==NULL) return 0;
49         else
50          if(cur->tail==1&&check(s+i,root))
51            return 1;
52          cur=cur->child[pos];
53     }
54     return 0;
55 }
56 int main()
57 {
58    int i=0,j;
59    #ifdef LOCAL
60    freopen("test.in","r",stdin);
61    #endif
62    Trie *root=(Trie *)malloc(sizeof(Trie));
63       root->tail=0;
64      for(j=0;j<26;j++)
65        root->child[j]=NULL;
66    while(scanf("%s",mat[i])!=EOF){
67      Insert(mat[i],root);
68      i++;
69    }
70   for(j=0;j<i;j++)
71   {
72       if(query(mat[j],root))
73         printf("%s\n",mat[j]);
74   }
75   return 0;
76 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-09-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Hat’s Words
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档