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;
}

转载于:https://www.cnblogs.com/martinue/p/5490536.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值