hdu1247-字典树,单词拆分

来源:互联网 发布:雨林木风xp优化工具 编辑:程序博客网 时间:2024/05/20 04:27

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

aahathathatwordhzieeword
 

Sample Output

ahathatword
 

这是一道比较水的字典树题目。就是问能不能在给出的单词中找出一个单词,这个单词是由词组里面的其他两个单词组成的;

思路很简单,就是建好树之后,然后把每个单词拆开,看在词组里面找得到对应的不?

就是一个很暴力的过程;


这里我要介绍一个库函数 strncpy(a,b,n);就是把b数组的前n项赋值给a;我也是看大神博客学到的,所以说看书很重要啊,头文件是<string.h>

#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#define inff 0x3fffffff
using namespace std;


struct node
{
    node *next[30];
    bool isword;
    node()
    {
        memset(next,NULL,sizeof(next));
        isword=false;
    }
};


void inse(node *root,char *s)
{
    int i;
    int len;
    int x;
    node *p;
    p=root;
    len=strlen(s);
    for(i=0;i<len;i++)
    {
        x=s[i]-'a';
        if(p->next[x]==NULL)
            p->next[x]=new node;
         p=p->next[x];
    }
    p->isword=true;
}
int query(node *root,char *s)
{
    int i,j;
    int  len;
    len=strlen(s);
    int x;
    node *p;
    p=root;
    for(i=0;i<len;i++)
    {
        x=s[i]-'a';
        if(p->next[x]==NULL)
            return 0;
         p=p->next[x];
    }
    if(p->isword==true)
        return 1;
    else return 0;
}
int dele(node *root)
{
    int i;
    for(i=0;i<26;i++)
    {
        if(root->next[i]!=NULL)
        {
            dele(root->next[i]);
        }
    }
    delete root;
}


char ss[50001][109];
int main()
{
    int i,j;
    node *root=new node;
    int sum=0;
    char str[1000];
    while(scanf("%s",str)!=EOF)
    {
        inse(root,str);
        strcpy(ss[sum],str);
        sum++;
    }
    int len;
    char fx[1000];
    char fy[1000];
    int flag1,flag2;
    for(i=0;i<sum;i++)
    {
        len=strlen(ss[i]);
        for(j=1;j<len-1;j++)
        {
            memset(fx,NULL,sizeof(fx)); ///  这里fx,fy一定要付初值,不然就会错,至于为什么,自己百度strncpy的说明
            memset(fy,NULL,sizeof(fy));
            strncpy(fx,ss[i],j);
            strncpy(fy,ss[i]+j,len-j);
            flag1=query(root,fx);
            flag2=query(root,fy);
            if(flag1&&flag2)
            {
                printf("%s\n",ss[i]);
                break;
            }
        }
    }
    dele(root);

}

0 0