題意:按字典序輸入一系列單詞,輸入結束後,判斷哪些單詞是由其餘兩個單詞串連而成。若是,則輸出(輸出也按字典序)。
#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;}