hdu1247 Hat’s Words(字典树)

判断某一个单词是否可以由另外两个单词组合而成,如果是则输出。


把所有单词边读入边插入字典树,树中值同样为某单词是否出现。然后遍历每个单词,再暴力求某单词是否由其他两个组成。由于只有一组数据,所以不存在什么超时爆内存。思路很清晰。

#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

typedef long long LL;

const int N = 30;
const int INF = 1e8;

struct Trie
{
    int sum;
    Trie *next[26];
    Trie()
    {
        sum = 0;
        for(int i = 0; i < 26; i ++)
            next[i] = 0;
    }
}*root;

int ans;

void inserttrie(Trie *p, char *str)
{
    int k = 0;
    while(str[k] != '\0')
    {
        int id = str[k] - 'a';
        if(p -> next[id] == 0)
        {
            p -> next[id] = new Trie;
        }
        p = p -> next[id];
        k ++;
    }
    if(p -> sum == 0) ans ++;
    p -> sum ++;//该单词是否出现过
}

int findtrie(Trie *p, char *str)
{
    int k = 0, num = 0;
    while(str[k] != '\0')
    {
        int id = str[k] - 'a';
        if(p -> next[id])
        {
            p = p -> next[id];
            num = p -> sum;
            k ++;
        }
        else return 0;
    }
    return num;
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[50005][N], a[N], b[N];
    int countt = 0;
    root = new Trie;
    while(~scanf("%s", s[countt]))
    {
        inserttrie(root, s[countt]);
        countt ++;
    }
    for(int i = 0; i < countt; i ++)
    {
        int len = strlen(s[i]), flag = 0;
        for(int j = 0; j < len; j ++)
        {
            memset(a, 0, sizeof(a));
            memset(b, 0, sizeof(b));
            int pos1 = 0, pos2 = 0;
            for(int l = 0; l < j; l ++)
            {
                a[pos1 ++] = s[i][l];
            }
            for(int l = j; l < len; l ++)
            {
                b[pos2 ++] = s[i][l];
            }
            if(findtrie(root, a) && findtrie(root, b)) flag = 1;
        }
        if(flag) printf("%s\n", s[i]);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值