1. 程式人生 > >Hat’s Words(字典樹的運用)

Hat’s Words(字典樹的運用)

註意 put ould truct size ++ 需要 sample pan

個人心得:通過這道題,對於樹的運用又加深了一點,字典樹有著他獨特的特點,那個指針的一直轉換著實讓我好生想半天,

不得不佩服這些發明算法人的大腦。

這題的解決方法還是從網上找到的,還好算法是自己實現得,沒錯!組合體只要進行分割再暴力搜索就好了,

步驟就是根據得到的字符串建立字典樹,然後一一找尋時,一次拆開,只要倆邊都滿足在字典樹裏面找的到就是我們所要找的了。

關於字典樹的建立的話,因為他是不知道子樹的,所以只要判斷出來不存在子樹就malloc一個就好了,

註意指針的指向和遞歸的奧妙,很多更新都是在遞歸中完成的,需要好好的體會。

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.

OutputYour 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
 1 #include <cstdio>
 2 #include <cstring>
 3 #include<iostream>
 4 #include <algorithm>
 5 #include <queue>
 6 #include<string>
 7 using namespace std;
 8 const int length=50;
 9 const int maxn=5005;
10 struct  word
11 {
12     word *next[length];
13     bool book;
14 15 }; 16 void insertword(word *root,char *s) 17 { 18 if(root==NULL||*s==\0) 19 return ; 20 word *p=root; 21 while(*s!=\0){ 22 if(p->next[*s-a]==NULL){ 23 word *q=(word *)malloc(sizeof(word)); 24 for(int i=0;i<length;i++) 25 q->next[i]=NULL; 26 q->book=false; 27 p->next[*s-a]=q; 28 p=p->next[*s-a]; 29 } 30 else 31 { 32 p=p->next[*s-a]; 33 34 } 35 s++; 36 } 37 p->book=true; 38 39 } 40 bool check(word *root,char x[],int y,int z){ 41 word *p=root; 42 for(int i=y;i<=z;i++) 43 { 44 if(p->next[x[i]-a]==NULL) return false; 45 p=p->next[x[i]-a]; 46 } 47 if(p->book==true) return true; 48 else return false; 49 50 } 51 bool searchword(word *root, char *s) 52 { 53 char x[100]; 54 int i=0; 55 while(*s!=\0) 56 { 57 x[i++]=*s; 58 s++; 59 } 60 for(int j=0;j<i-1;j++) 61 { 62 if(check(root,x,0,j)&&check(root,x,j+1,i-1)){ 63 return true; 64 } 65 } 66 return false; 67 68 } 69 char st[50005][100]; 70 int main() 71 { 72 word *root=(word *)malloc(sizeof(word)); 73 root->book=false; 74 int i; 75 for(i=0;i<length;i++) 76 root->next[i]=NULL; 77 i=0; 78 while(scanf("%s",st[i])!=EOF) 79 { 80 insertword(root,st[i]); 81 i++; 82 } 83 for(int j=0;j<i;j++) 84 { 85 if(searchword(root,st[j])) 86 cout<<st[j]<<endl; 87 } 88 return 0; 89 }



Hat’s Words(字典樹的運用)