HDU 1247 Hat’s Words (字典树)

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

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<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

typedef struct Trie_Node
{
    bool isWord;
    struct Trie_Node *next[26];
}Trie;
char s[50010][50];

void Trie_insert(Trie *root,char *str)
{
    Trie *p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int k=str[i]-'a';
        if(p->next[k]==NULL)
        {
            Trie *t=new Trie;
            for(int j=0;j<26;j++) t->next[j]=NULL;
            t->isWord=false;
            p->next[k]=t;
        }
        p=p->next[k];
    }
    p->isWord=true;
}
bool Trie_search(Trie *root,char *str)
{
    Trie *p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int k=str[i]-'a';
        if(p->next[k]==NULL) return false;
        p=p->next[k];
    }
    return p->isWord;
}
void Trie_del(Trie *root)
{
    for(int i=0;i<26;i++)
    {
        if(root->next[i]!=NULL)
            Trie_del(root->next[i]);
    }
    free(root);
}

int main()
{
    int tot=0;
    Trie *root=new Trie;
    for(int i=0;i<26;i++)
        root->next[i]=NULL;
    root->isWord=false;
    while(scanf("%s",s[tot])!=EOF)
    {
        Trie_insert(root,s[tot++]);
    }
    for(int i=0;i<tot;i++)
    {
        int len=strlen(s[i]);
        for(int j=1;j<len-1;j++)
        {
            char temp1[50]={'\0'};
            char temp2[50]={'\0'};
            strncpy(temp1,s[i],j);
            strncpy(temp2,s[i]+j,len-j);
            if(Trie_search(root,temp1)&&Trie_search(root,temp2))
            {
                printf("%s\n",s[i]);
                break;
            }
        }
    }
    Trie_del(root);
    return 0;
}

 

posted @ 2016-08-04 21:02  季末Despair  阅读(166)  评论(0编辑  收藏  举报