集训队专题(1)1007 Hat’s Words

Hat’s Words

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 36   Accepted Submission(s) : 15
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
戴帽子的
 

       此题是字典树的一个变形(小编看网上有大神没用字典树就AC的……牛逼啊)。由于需要判断是否为一个词的结尾,故需要在结构体定义的时候加一项bool变量来判断。此题小编是先把所有的节点先建立好再进行搜索的,当然要是大神够6可以在建立节点的同时进行搜索(小编我也是个辣鸡TT,同求大神的方法)。

#include <iostream>  
#include <string.h>
#include <cstdio>
#define MAX 50005
using namespace std;  
char word[MAX][16];  //这道题16就足够了  
struct TrieNode  
{  
   bool is;  
   TrieNode *next[26];  
   TrieNode()  
   {  
      is=false;  
      memset(next,0,sizeof(next));  
   }  
};  
void InsertTrie(TrieNode *pRoot,char s[])  
{  
    int i;  
    TrieNode *p=pRoot;  
    i=0;  
    while(s[i])  
    {  
         int k=s[i]-'a';  
         if(p->next[k]==NULL)  
            p->next[k]=new TrieNode();  
         i++;  
         p=p->next[k];  
    }  
    p->is=true; //该结点是单词的尾  
}
bool Search(TrieNode *pRoot,char s[])  
{  
    int i,top=0,stack[1000];//模拟栈 
    TrieNode *p=pRoot;  
    i=0;  
    while(s[i])  
    {  
        int k=s[i++]-'a';  
        if(p->next[k]==NULL)  
            return 0;  
        p=p->next[k];  
        if(p->is && s[i]) //找到该单词含有子单词的分隔点  
            stack[top++]=i;//入栈  
    }  
    while(top)//从可能的分割点去找  
    {  
        bool ok=1;  
        i=stack[--top];  
        p=pRoot;  
        while(s[i])  
        {  
            int k=s[i++]-'a';  
            if(p->next[k]==NULL)  
            {  
                ok=false;  
                break;  
            }  
            p=p->next[k];  
        }  
        if(ok && p->is)//找到最后,并且是单词的  
            return 1;  
    }  
    return 0;  
}
int main()  
{  
    int i=0;  
    TrieNode *pRoot=new TrieNode();  
    while(gets(word[i]))  
    {  
        InsertTrie(pRoot,word[i]);  
        i++;  
    }  
    for(int j=0;j<i;j++)  
        if(Search(pRoot,word[j]))  
            cout<<word[j]<<endl;  
    return 0;  
}  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值