Hat’s Words (hdu 1247) (字典树)

 

Time limit   1000 ms

Memory limit   32768 kB

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

WA了好几发,带着疑问查看了别人的题解,发现是自己题目意思理解错了。其实就是字典树的变形!!!

解题思路来自:https://blog.csdn.net/u012860063/article/details/39022747

#include<bits/stdc++.h>
using namespace std;
const int maxn=26;
char str[50017][117];
char x[117],y[117];
struct trie
{
    trie *next[maxn];
    int v;
}*a;
void init()
{
    a=new trie;
    for(int i=0;i<maxn;i++)
        a->next[i]=NULL;
}
void trie_insert(char *s)
{
    int n=strlen(s);
    trie *p=a,*q;
    for(int i=0;i<n;i++)
    {
        int id=s[i]-'a';
        if(p->next[id]==NULL)
        {
            p->next[id]=new trie;
            p=p->next[id];
            p->v=1;
            for(int j=0;j<maxn;j++)
                p->next[j]=NULL;
        }
        else p=p->next[id];
    }
    p->v=-1;//单词结尾
}
int Findtrie(char *s)
{
    int n=strlen(s);
    trie *p=a;
    for(int i=0;i<n;i++)
    {
        int id=s[i]-'a';
        if(p->next[id]==NULL) return 0;
        p=p->next[id];
    }
    if(p->v==-1) return -1;
    else return 0;
}
int deletetrie(trie *T)
{
    if(!T) return 0;
    for(int i=0;i<maxn;i++)
        if(T->next[i]) deletetrie(T->next[i]);
    delete T;
    return 0;
}
int main()
{
    init();
    int cnt=0;
    while(scanf("%s",str[cnt])==1)
    {
        trie_insert(str[cnt]);
        cnt++;
    }
    for(int i=0;i<cnt;i++)
    {
        int n=strlen(str[i]);
        for(int j=1;j<n;j++)
        {
            strncpy(x,str[i],j);
            x[j]='\0';
            strncpy(y,str[i]+j,n-j);
            y[n-j]='\0';
            if(Findtrie(x)==-1&&Findtrie(y)==-1)
            {
                printf("%s\n",str[i]);
                break;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值