hud 1247 Hat’s Words字典树单词匹配

Hat’s Words

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


 

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

 

Author

戴帽子的

 

Recommend

Ignatius.L   |   We have carefully selected several similar problems for you:  1075 1298 1800 2846 1305 

 把单词分两段分别进行匹配

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int ch[100005][26];
int val[100005];
int sz;
void init()
{memset(ch,0,sizeof(0));
    sz=0;
}
void insert(char*s)
{
    int u=0,n=strlen(s);
    for(int i=0;i<n;i++)
    {
        int id=s[i]-'a';
        if(ch[u][id]==0)
        {
            ch[u][id]=++sz;
            memset(ch[sz],0,sizeof(ch[sz]));
            val[sz]=0;
        }
        u=ch[u][id];
    }
    val[u]=1;
}
bool find(char*s)
{
    int u=0,n=strlen(s);
    for(int i=0;i<n;i++)
    {
        int id=s[i]-'a';
        if(ch[u][id]==0)
            return false;
        u=ch[u][id];

    }
    return val[u];
}
char word[500005][105];
int main()
{
    init();
    int cnt=0;
   while(gets(word[cnt]))
    {
        insert(word[cnt++]);
    }
    for(int i=0;i<cnt;i++)
    {
        int len=strlen(word[i]);
        for(int j=1;j<len;j++)
        {
            char str1[100];
            char str2[100];
            strncpy(str1,word[i],j);
            str1[j]=0;
            strncpy(str2,word[i]+j,len-j);
            str2[len-j]=0;
            if(find(str1)&&find(str2))
            {
                printf("%s\n",word[i]);
                break;
            }
        }
    }
    return 0;

}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/83959420