1. 程式人生 > >HDU 1247 Hat’s Words(字典樹)

HDU 1247 Hat’s Words(字典樹)

ota log ted family lar line 初始 ber problems

Hat’s Words

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


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 | We have carefully selected several similar problems for you: 1075 1298 1800 2846 1305 題意是 在輸入的字符串中,如果一個字符串能由另外兩個字符串拼接而成,就輸出這個字符串 分析: 枚舉每一個字符串分成兩個字符串的結果,看這兩個字符串是否能夠找到 代碼如下:
#include <cstdio>
#include <iostream>
#include 
<cstring> using namespace std; const int MAXN=26; //只有小寫字母 typedef struct Trie{ bool v; Trie *next[MAXN]; }Trie; Trie *root; char s1[100]; char s2[100]; void createTrie(char *str) { int len=strlen(str); Trie *p=root,*q; for(int i=0;i<len;i++) { int id=str[i]-a; if(p->next[id]==NULL) { q=(Trie*)malloc(sizeof(Trie)); q->v=false; //每次建立新節點進行初始化操作 for(int j=0;j<MAXN;j++) q->next[j]=NULL; p->next[id]=q; p=p->next[id]; } else { // p->next[id]->v=false; p=p->next[id]; } } if(p!=root) //p==root 代表讀入的是空串 p->v=true; //表示以此結點結尾的字符串存在 } bool findTrie(char *str) { int len=strlen(str); Trie *p=root; for(int i=0;i<len;i++) { int id=str[i]-a; p=p->next[id]; if(p==NULL) return false; } return p->v; } int deal(Trie *T) { int i; if(T==NULL) return 0; for(int i=0;i<MAXN;i++) { if(T->next[i]!=NULL) deal(T->next[i]); } free(T); return 0; } int main() { char str[50010][100]; int t,n,flag,cnt; root=(Trie*)malloc(sizeof(Trie)); for(int i=0;i<MAXN;i++) root->next[i]=NULL; root->v=false; //初始化 cnt=0; while(gets(str[cnt])) { createTrie(str[cnt]); cnt++; } // cout<<findTrie("a")<<" "<<findTrie("hat")<<endl; for(int k=0;k<cnt;k++){ n=strlen(str[k]); for(int i=1;i<=n;i++) { for(int j=0;j<i;j++) s1[j]=str[k][j]; s1[i]=\0; for(int j=i;j<=n-1;j++) s2[j-i]=str[k][j]; s2[n-i]=\0; if(findTrie(s1)&&findTrie(s2)) { printf("%s\n",str[k]); break; } } } deal(root); return 0; }

HDU 1247 Hat’s Words(字典樹)