(字典树)Hat’s Words -- HDOJ

来源:互联网 发布:十秒竞拍源码 编辑:程序博客网 时间:2024/06/07 13:40

Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 308 Accepted Submission(s): 142

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

/*    根据每个单词建立一棵树    对每个单词拆成两部分,分别对这两部分去树中查找,    判断是否这两部分,都在树中,若都在,则说明这个单词    是由两个单词组成的*/#include<iostream>#include<stdio.h>#include<algorithm>#include<string>#include<string.h>#include<math.h>#include<map>#include<set>#include<string>#define mod 1000000007using namespace std;typedef struct Node{    bool is;    Node *nxt[27];//26个英文字母    Node()    {        is = false;//is为true,则代表一个单词的结束        memset(nxt,0,sizeof(nxt));    }}Node;string word[50005];void Insert(Node * root,string s){    int indx=0;    Node *p = root;    while(indx<s.size())//将单词的每个字母都插入到树中    {        int k = s[indx++] - 'a';        if(p->nxt[k] == 0)//如果k位置不存在,我们就新生成一个节点            p->nxt[k] = new Node();        p = p->nxt[k];    }    p->is = true;//单词插入结束,做标记}bool Search(Node *root,string s){    Node *p = root;    int indx = 0;    while(indx < s.size())    {        int k = s[indx++] - 'a';        if(p->nxt[k] == 0)//要查询的第indx个字母不存在,则单词不在这个树中            return 0;        p = p->nxt[k];    }    if(p->is)//查询完整个单词,正好到达单词结束的标记地方        return 1;    return 0;}int main(void){ //   freopen("in.txt","r",stdin);    int indx = 0;    Node *root = new Node();    while(cin>>word[indx])    {        Insert(root,word[indx++]);    }    for(int i=0; i<indx; ++i)    {        bool flg = false;        for(int j=1; j<word[i].size(); ++j)        {            //将单词分割成两部分            string str1 = word[i].substr(0,j);            string str2 = word[i].substr(j,word[i].size()-j);            //其中有个为空,则不做操作            if(!str1.size() || !str2.size())                continue;            //两部分都满足在树中            if(Search(root,str1) && Search(root,str2))            {                flg = true;                break;            }        }        if(flg)            cout << word[i]<<endl;    }    return 0;}
原创粉丝点击