题意:给出n个单词(1<=n<=1000),求出每个单词的非公共前缀,如果没有,则输出自己。 思路:基础的trie。 源代码:(428K,0MS) #include<iostream> using namespace std; const int Max = 1002; const int branchNum = 26; struct tree_node{ int count; // 记录用到这个节点的单词数量,如果=1,则证明其为这个单词唯一的节点。 tree_node *next[branchNum]; }root, node[20*Max]; int p = 0; void insert(char *word){ tree_node *location = &root; while(*word){ if(location->next[*word-'a'] == NULL){ node[p].count = 0; location->next[*word-'a'] = &node[p ++]; } location = location->next[*word-'a']; location->count ++; word ++; } } void search(char *word){ tree_node *location = &root; while(*word && location){ if(location->count == 1) break; printf("%c", *word); location = location->next[*word-'a']; word ++; } printf("/n"); } int main(){ char word[Max][21]; int i, k = 0; while(scanf("%s", word[k]) != EOF){ insert(word[k]); k ++; } for(i = 0; i < k; i ++){ printf("%s ", word[i]); search(word[i]); } return 0; }