码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1247 Hat’s Words 字典树

时间:2015-08-08 11:43:22      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

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
 
         字典树:以给的每个单词建树。然后给每个单词分成两半查找,如果两半都在树中查找到了,就输出者个单词。
 
     
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[50005][50];
struct f
{
    int next[30];
    int v;
    void ff()
    {
        memset(next,-1,sizeof(next));
        v=0;
    }
};f tree[1000000];
int cut=0;
void buld(char *s1)
{
    int i,k=0,su;
    for (i=0;s1[i]!=‘\0‘;i++)
    {
        su=s1[i]-‘a‘;
        if (tree[k].next[su]==-1)
        {
            cut++;
            tree[k].next[su]=cut;
            tree[cut].ff();
        }
        k=tree[k].next[su];
    }
    tree[k].v=1;
    return ;
}
int find(char *s1)
{
    int i,k=0,su,len;
    len=strlen(s1);
    for (i=0;i<len;i++)
    {
        su=s1[i]-‘a‘;
        if (tree[k].next[su]==-1) break;
        k=tree[k].next[su];
    }
    if (i==len&&tree[k].v) return 1;
    return 0;
}
int main()
{
     int p=0,i,j,len,k,d;
     char sl[50],sr[50];
     tree[cut].ff();
     while (~scanf("%s",s[p]))
     {
         buld(s[p]);
         p++;
     }
     for (i=0;i<p;i++)
     {
         len=strlen(s[i]);
         for (j=0;j<len;j++)
         {
             memset(sr,‘\0‘,sizeof(sr));
             memset(sl,‘\0‘,sizeof(sl));
            for (k=0;k<j;k++) sl[k]=s[i][k];
            sl[j]=‘\0‘;
            for (k=j,d=0;k<len;k++,d++) sr[d]=s[i][k];
            sr[len]=‘\0‘;
             if (find(sl)&&find(sr))
             {
                 printf("%s\n",s[i]);
                 break;
             }
         }
     }
     return 0;
}

 

hdu 1247 Hat’s Words 字典树

标签:

原文地址:http://www.cnblogs.com/pblr/p/4712733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!