HDU1247 字典树 Hat’s Words(Tire Tree)
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18399????Accepted Submission(s): 6532
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:??1251?1075?1671?1298?1800?
題意:
給定一些單詞,要你從中找到某些單詞,而這個單詞是由另外兩個單詞組成的。
其實我們就是利用字符的ascii碼來給他對應的索引,就是把每個單詞拆成兩部分,看看是不是每一部分在字典樹中都是一個單詞
比如說建樹的時候存儲apple這個單詞,對應如下圖
在算法導論中,Trie并不叫字典樹,而叫基數樹,實際上并不是只與字典樹有關,是一個N叉樹。字典樹的功能是對于很多串進行壓縮,壓縮的方法是跟據這個字符串的前綴,每個節點表示一個字符,從根節點到葉子節點表示一個字符串。
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int MAX = 26; struct Trie {Trie *next[MAX];bool isword; }; Trie *root = new Trie; char word[50000][30]; void createTrie(char str[]) {int len = strlen(str);Trie *p = root,*q = NULL;for(int i=0;i<len;i++){int id = str[i]-'a';if(p->next[id]==NULL){q = new Trie;for(int j=0;j<MAX;j++)q->next[j] = NULL;q->isword = false;p->next[id] = q;}if(i==len-1)p->next[id]->isword = true;p = p->next[id];}} bool findTrie(char str[]) {int len = strlen(str);Trie *p = root;for(int i=0;i<len;i++){int id = str[i]-'a';if(p->next[id]==NULL){return false;}p = p->next[id];}if(p->isword)return true;elsereturn false; } void del(Trie *root) {for(int i=0;i<MAX;i++){if(root->next[i]!=NULL){del(root->next[i]);}}delete root; } int main() {int num=0;char str1[30],str2[30];for(int i=0;i<MAX;i++){root->next[i] = NULL;}root->isword = false;while(gets(word[num])){createTrie(word[num]);num++;}for(int i=0;i<num;i++){int len = strlen(word[i]);if(len==1)continue;for(int j=0;j<len;j++)//從每個單詞的各部分拆開{int k;if(j==len-1) continue;for(k=0;k<=j;k++){str1[k] = word[i][k];}str1[k]='\0';int k2=0;for(int l=k;l<len;l++){str2[k2++]=word[i][l];}str2[k2]='\0';if(findTrie(str1)&&findTrie(str2)){cout<<word[i]<<endl;break;//居然錯在這里了(可能會重復輸出)}}}del(root);return 0; }?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的HDU1247 字典树 Hat’s Words(Tire Tree)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU2176 【 Nim博弈】 SG
- 下一篇: 01背包问题+完全背包问题+多重背包问题