字典樹(TrieTree),常見應用於大量字串的儲存,統計,尋找等操作,由於字串的公用首碼沒有重複儲存,所以操作起來比較方便,效率很高,搜尋引擎的文本詞頻統計就是它的經典應用之一。
HDU1251 統計難題
題目要求計算一個給定字串在特定字元集中以某個單詞的首碼身份出現的次數,裸字典樹……
CODE:
#include<stdio.h>const int MAX = 26;typedef struct TrieNode{int nodeCount;struct TrieNode *next[MAX];}TrieNode,* TrieTree;//借鑒別人的方法,申請靜態空間,比malloc方便一些//出自:http://www.cnblogs.com/DiaoCow/archive/2010/04/19/1715337.htmlTrieNode Memory[1000000];int index=0;TrieTree CreateTree(){TrieNode *p;p = &Memory[index++];p->nodeCount = 1;for(int i=0;i<MAX;i++){p->next[i] = NULL;}return p;}void InsertTrie(TrieTree * root,char *s){TrieTree p;p = * root;for(int i=0;s[i];i++){int k = s[i] - 'a';if(p->next[k])p->next[k]->nodeCount++;elsep->next[k] = CreateTree();p = p->next[k];}}int SearchTrie(TrieTree * root,char *s){TrieTree p = * root;for(int i=0;s[i];i++){int k = s[i]-'a';if(p->next[k] == NULL)return 0;p = p->next[k];}return p->nodeCount;}void Delete(TrieTree p){if(p!=NULL){for(int i=0;i<MAX;i++){if(p->next[i] != NULL)Delete(p->next[i]);delete p;p = NULL;}}}int main(){char str[11];TrieTree root = CreateTree();while(gets(str) && str[0]){InsertTrie(&root,str);}while(gets(str)){printf("%d\n",SearchTrie(&root,str));}return 0;}