HDU1247 Hat's Words(Trie树,map)

来源:互联网 发布:ipad淘宝可以看直播吗 编辑:程序博客网 时间:2024/06/10 00:43

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

aahathathatwordhzieeword

Sample Output

ahathatword

思路

先把每一个单词都插入字典树中,然后在利用字典树的递归进行查询.

还可以利用map建立映射,然后枚举

代码

#include <cstdio>#include <cstring>#include <string>#include <set>#include <sstream>#include <cmath>#include <iostream>#include <stack>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define debug() puts("what the fuck!!!")#define ll long longusing namespace std;const int N=50020*4;struct dicTree{    struct node    {        int sum;        int next[26];    } Tree[N];    int root,sz;    int newnode()    {        for(int i=0; i<26; i++)            Tree[sz].next[i]=-1;        Tree[sz++].sum=0;        return sz-1;    }    void init()    {        sz=0;        root=newnode();    }    void insert(string s)    {        int now=root;        int len=s.length();        for(int i=0; i<len; i++)        {            int to=s[i]-'a';            if(Tree[now].next[to]==-1)                Tree[now].next[to]=newnode();            now=Tree[now].next[to];        }        Tree[now].sum++;    }    int find(string s,int start,int len)    {        int now=root;        for(int i=start; i<len; i++)        {            int to=s[i]-'a';            if(Tree[now].next[to]==-1)                return 0;            if(Tree[now].sum&&(!start)&&find(s,i,len))                return 1;            now=Tree[now].next[to];        }        if(start&&Tree[now].sum)            return 1;        return 0;    }};dicTree T;string input[N];int main(){    T.init();    int cnt=0;    while(cin>>input[cnt])        T.insert(input[cnt++]);    for(int i=0; i<cnt; i++)        if(T.find(input[i],0,input[i].length()))            cout<<input[i]<<endl;    return 0;}

map:

#include <bits/stdc++.h>using namespace std;const int N=50020;map<string,int>mp;string str[N];int main(){    int cnt=0;    while(cin>>str[cnt])        mp[str[cnt++]]=1;    for(int i=0; i<cnt; i++)        for(int j=1; j<str[i].length()-1; j++)        {            string s1(str[i],0,j);            string s2(str[i],j);            if(mp[s1]&&mp[s2])            {                cout<<str[i]<<endl;                break;            }        }    return 0;}
原创粉丝点击