HDU-1247-Hat’s Words(字典树)

Hat’s Words

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

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

题意:给出很多单词,如果存在两个单词连接在一起能组成单词表中的另一个单词,就输出另一个单词,按照字典序输出所有结果。

思路:对于一张字典表,建立正向和反向两棵字典树,深搜正向枚举所有单词,取反后判断是否存在两个单词组成当前枚举的单词。

代码

#include
#include
#include
#include
using namespace std;
//这个字典树好难
const int maxn=27;
struct Trie
{
    Trie *ch[maxn];
    bool flag;//标记从根节点到此结点是一个完整的单词
};
Trie root_1,root_2;//两个根节点对应两棵字典树
bool flag_1[maxn],flag_2[maxn];
char str_1[maxn],str_2[maxn];
void Insert_1(char *str)
{
    Trie *p=&root_1,*q;
    int len=strlen(str);
    for(int i=0; iint point=str[i]-'a';
        if(p->ch[point]==NULL)
        {
            q=(Trie *)malloc(sizeof(Trie));
            q->flag=false;
            for(int j=0; jch[j]=NULL;
            p->ch[point]=q;
        }
        p=p->ch[point];
    }
    p->flag=true;//从根节点到当前结点是一个完整的单词
}
void Insert_2(char *str)
{
    Trie *p=&root_2,*q;
    int len=strlen(str);
    for(int i=0; iint point=str[i]-'a';
        if(p->ch[point]==NULL)
        {
            q=(Trie *)malloc(sizeof(Trie));
            q->flag=false;
            for(int j=0; jch[j]=NULL;
            p->ch[point]=q;
        }
        p=p->ch[point];
    }
    p->flag=true;//从根节点到但前节点是一个完整的单词
}
void check_2(char *str)//保存出现过的所有前缀状态
{
    Trie *p=&root_2;
    int len=strlen(str);
    for(int i=0; iif(p->flag)
            flag_2[i]=true;
        int point=str[i]-'a';
        if(p->ch[point]==NULL)
            return;
        p=p->ch[point];
    }
}
void Getstr_2(char *str)//获取反串
{
    int len=strlen(str);
    for(int i=0; i1]=str_1[i];
    str_2[len]='\0';
}
void DFS(Trie *from,int i)
{
    if(from->flag)
    {
        str_1[i]='\0';
        Getstr_2(str_1);
        memset(flag_2,false,sizeof(flag_2));
        check_2(str_2);
        int len=strlen(str_1);
        for(int j=1; jif(flag_1[j]&&flag_2[len-j])
            {
                printf("%s\n",str_1);
                break;
            }
        }
        flag_1[i]=true;
    }
    for(int j=0; jif(from->ch[j])
        {
            str_1[i]=j+'a';
            DFS(from->ch[j],i+1);
        }
    }
    flag_1[i]=false;
}
int main()
{
    root_1.flag=false;
    root_2.flag=false;
    for(int i=0; iwhile(scanf("%s",str_1)!=EOF)
    {
        Insert_1(str_1);
        Getstr_2(str_1);
        Insert_2(str_2);
    }
    DFS(&root_1,0);
    return 0;
}

你可能感兴趣的:(字符串)