hdu 1247/哈理工oj 2057 Hat’s Words【字典树】

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11951    Accepted Submission(s): 4272


Problem 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
 

很经典的一道tire树问题、因为数据量比较大,用strstr和strcat是会超时的,所以我们这里应用字典树查找的方法来解题

思路:

1、把所有给出的单词入树(入字典)。

2、对所有单词这样查找:如果在这个单词还没查到结尾的时候,在树里边找到了一个单词,那么从这个位子出发找下一个单词,如果找到了,输出。

最后注意一下flag标记的位子和读取的位子就好:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define maxn 26
typedef struct tree
{
    int flag;
    tree *next[maxn];
}tree;
char str[50005][20];
char ans[50005][20];
tree root;
void creat(char *str)
{
    int len=strlen(str);
    tree *p=&root,*q;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
        {
            q=(tree *)malloc(sizeof(root));
            for(int j=0;j<26;j++)
            {
                q->next[j]=NULL;
            }
            p->next[id]=q;
        }
        p=p->next[id];
        if(i==len-1)
        {
            p->flag=1;
        }
    }
}
int findnext(char *str)
{
    int len=strlen(str);
    tree *p=&root;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        p=p->next[id];
        if(p==NULL)
        return 0;
    }
    return p->flag;//不能找到这里就直接return 1、在这里wa了N发~
}
int find(char *str)
{
    int len=strlen(str);
    tree *p=&root;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        p=p->next[id];
        if(p==NULL)
        return 0;
        if(p->flag==1&&findnext(str+i+1)==1&&i!=len-1)
        return 1;
    }
    return 0;
}
int main()
{
    int j=0;
    for(int i=0;i<26;i++)
    {
        root.flag=0;
        root.next[i]=NULL;
    }
    while(scanf("%s",str[j])!=EOF)
    {
        getchar();
        creat(str[j]);
        //if(str[j][0]=='e')break;
        j++;
    }
    int cont=0;
    for(int i=0;i<j;i++)
    {
        if(find(str[i])==1)
        {
            printf("%s\n",str[i]);
        }
    }
    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值