字典树典型应用(1247)

来源:互联网 发布:知乎电脑版下载官网 编辑:程序博客网 时间:2024/06/05 23:41

Hat’s Words

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


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

/*------------------Header Files------------------*/#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>#include <cstdlib>#include <ctype.h>#include <cmath>#include <stack>#include <queue>#include <deque>#include <map>#include <vector>#include <set>#include <limits.h>using namespace std;/*------------------Definitions-------------------*/#define LL long long#define uLL unsigned long long#define PI acos(-1.0)#define INF 0x3F3F3F3F#define MOD 9973#define MAX 105#define lson rt<<1,l,m#define rson rt<<1|1,m+1,r/*---------------------Work-----------------------*/char word[50050][30];struct node{bool isWord;node *next[30];node(){isWord=false;memset(next,0,sizeof(next));}};void insert(node *rt,char *s){int i=0;node *p=rt;while(s[i]){int temp=s[i++]-'a'; //所属分支if(p->next[temp]==NULL)p->next[temp]=new node();p=p->next[temp];}p->isWord=true;}bool searchWord(node *rt,char *s){stack<int>mystack;int i=0;node *p=rt;while(s[i]){int temp=s[i++]-'a';if(p->next[temp]==NULL) return false;p=p->next[temp];if(p->isWord&&s[i])mystack.push(i);}while(!mystack.empty()){bool flag=true;i=mystack.top();mystack.pop();p=rt;while(s[i]){int temp=s[i++]-'a';if(p->next[temp]==NULL){flag=false;break;}p=p->next[temp];}if(flag&&p->isWord) return true;}return false;}void work(){int i=0;node *rt=new node();while(scanf("%s",word[i])==1){insert(rt,word[i]);i++;}//for(int j=0;j<i;j++)//printf("%s\n",word[j]);for(int j=0;j<i;j++)if(searchWord(rt,word[j]))printf("%s\n",word[j]);}/*------------------Main Function------------------*/int main(){//freopen("test.txt","r",stdin);work();return 0;}



0 0
原创粉丝点击