字典树hdu1247

题意:如果有个单词是由其它两个单词组成的,就输出。

思路:每个结点加个标志位,判断是不是一个完整的单词。如果进行查找操作,查找成功之后,把查找成功的部分截掉,查找剩下的部分,如果也查找成功,那就输出。比如“a ahat hat”,”ahat”在字典树中查找时,找到’a’是一个单词,截掉’a’的部分,剩下”hat”,继续找,找到了”hat”,就证明是由两个单词组成的了。

#include <iostream>
using namespace std;
#include <cstdio>
#include <cstring>
#include <malloc.h>
char s[50001][100];
struct Trie
{
    int isWord;
    Trie *next[26];
};
void Init(Trie *t) //初始化结点
{
    t->isWord = 0;
    for(int i = 0; i < 26; i++)
    {
        t->next[i] = NULL;
    }
}
void Insert(Trie *t, char s[]) //建树
{
    Trie *temp = t;
    int len = strlen(s);
    for(int i = 0; i<  len; i++)
    {
        if(temp->next[s[i]-'a'] == NULL)
        {
            temp->next[s[i]-'a'] = (Trie*)malloc(sizeof(Trie));
            Init(temp->next[s[i]-'a']);
        }
        temp = temp->next[s[i]-'a'];
    }
    temp->isWord = 1;
}
int Search(Trie *t, char s[]) //查找操作
{
    Trie *temp = t;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(temp->next[s[i]-'a'] == NULL)
            return 0;
        temp = temp->next[s[i]-'a'];
    }
    if(temp->isWord)
    {
        return 1;
    }
    return 0;
}
int main()
{
    char word[100];
    Trie *root = (Trie*)malloc(sizeof(Trie));
    Init(root);
    int key = 0;
    while(gets(word)!=NULL)
    {
        strcpy(s[key], word);
        Insert(root, word);
        key++;
    }
    for(int i = 0; i < key; i++)
    {
        int len = strlen(s[i]);
        for(int j = 1; j < len; j++) 
        {
            char a[100];
            strncpy(a, s[i], j);  
            a[j] = '\0'; 
            if(Search(root, a))  //查找成功了之后
            {
                char b[100];
                strncpy(b, s[i]+j, len-j);
                b[len-j] = '\0';
                if(Search(root, b))  //截掉前部分,继续查找
                {
                    puts(s[i]);  //输出该字符串
                    break; 
                }
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值