HDU 1247 Trie樹

來源:互聯網
上載者:User

題意:按字典序輸入一系列單詞,輸入結束後,判斷哪些單詞是由其餘兩個單詞串連而成。若是,則輸出(輸出也按字典序)。

#include <iostream>using namespace std;char list[50001][26];const int kind = 26;int cnt = 0;struct Treenode{bool flag;Treenode *next[kind];Treenode(){flag = false;for ( int i = 0; i < kind; ++i )next[i] = NULL;}} node[100000];void Insert ( Treenode *&root, char *word ){Treenode *location = root;if ( location == NULL ){location = &node[cnt++];root = location;}int id, i = 0;while ( word[i] ){id = word[i] - 'a';if ( location->next[id] == NULL )location->next[id] = &node[cnt++];location = location->next[id];++i;}location->flag = true; /*注意標記單詞的最後一個字母,說明在這之前的字母組成一個單詞,以便查詢時劃分*/}bool check ( Treenode *root, char* word ){Treenode *location = root;if ( location == NULL ) return false;int id, i = 0, len = strlen(word);while ( word[i] ){id = word[i] - 'a';if ( location->next[id] == NULL )return false;if ( i == len-1 && location->next[id]->flag == true )return true;/*尋找到最後一個字元時,節點的標記應該是true,這樣才是完全符合的*/location = location->next[id];++i;}return false;}bool Search ( Treenode *root, char * word ){Treenode *location = root;if ( location == NULL ) return false;int id, i = 0, len = strlen(word);while ( word[i] ){id = word[i] - 'a';if ( location->next[id] == NULL )return false;if ( location->next[id]->flag == true )/*當檢測到一個標記時說明單詞的前半部分已經檢測到,現在只需檢測後面一部分是否能由另一個單詞構成*/{if ( i + 1 < len && check(root,&word[i+1]) )return true;}location = location->next[id];++i;}return false;}int main(){int i = 0, j;Treenode *root = NULL;while ( scanf("%s", list[i]) != EOF ){Insert(root,list[i]);++i;}for ( j = 0; j < i; ++j ){if ( Search(root,list[j]) )printf("%s\n",list[j]);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.