hdu1247(trie树)

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


简单的trie树,构建trie树之后在把单词一个个分开遍历查找,没什么复杂。


#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
const int NODE = 1e6+10,CH = 26;
int ch[NODE][CH],sz,val[NODE];
char a1[100001][15],a2[15];
    /**
    ch[u][c]:   节点u指向的c儿子的边
    val[u]:     节点u的值
    sz:         trie树的size
    */
int idx(char c)
{return c-'a';}
int node()
{
        memset(ch[sz],0,sizeof(ch[sz]));
        ///将所有儿子置为空
        val[sz]=0;
        return sz++;
}
void init()
{
        sz=0;
        ///trie树根节点为下标0的节点
        node();
}
void insert(char *s,int v)
{
        int u=0;
        for(;*s;s++)
        {

            int c=idx(*s);
            ///如果节点不存在 新建节点 并把值赋给当前节点的c儿子边
            if(!ch[u][c])
                ch[u][c]=node();
            ///继续移动
          //  cout<<u<<' '<<char(c+'a')<<' '<<ch[u][c]<<endl;
            u=ch[u][c];
        }
        ///在末尾节点记录信息
        val[u]=v;
}
int find(char *s)
{
    int u=0;
    for(;*s;s++)
    {
        int c=idx(*s);
       // cout<<u<<' '<<(char)(c+'a')<<' '<<num[u]<<endl;
        ///如果u节点没有c儿子  结束
            if(!ch[u][c])
            return 0;
            u=ch[u][c];
       // cout<<(char)*s<<endl;
    }
    return val[u];
}
int main()
{
    int o=0;
    init();
    while(~scanf("%s",a1[o++]))
    {
        insert(a1[o-1],o);//if(o==8)break;
    }
    for(int i=0;i<o;i++)
    {
        int l=strlen(a1[i]);
        if(l>1)
        {
            for(int j=0;j<l-1;j++)
            {
                int k,kk=0;
                char mm1[20],mm2[20];
                for(k=0;k<=j;k++)
                mm1[k]=a1[i][k];
                mm1[k]='\0';
                for(;k<l;k++)
                mm2[kk++]=a1[i][k];
                mm2[kk]='\0';
                if(find(mm1)!=0&&find(mm2)!=0)
                {
                    //cout<<mm1<<' '<<mm2<<endl;

                   printf("%s\n",a1[i]);break;
                }
            }
        }
    }
    return 0;
}

posted @ 2015-08-12 15:07  martinue  阅读(169)  评论(0编辑  收藏  举报