利用公共前綴減少查詢時間,節省內存
靜態分配,動態分配malloc次數太多,效率不行
const int maxc = 26;
const int maxn = 1000010;
typedef struct trie{
int v;
struct trie *next[maxc];
}trie;
trie mem[maxn];
int alloc;
void init(trie **root){
alloc = 0;
*root = create();
}
trie *create(){
trie *p = &mem[alloc++];
p->v = 0;
for(int i = 0; i < maxc; ++i){
p->next[i] = NULL;
}
return p;
}
void insert(trie *root, char *s){
while(*s){
int b = *s - 'a';
++s;
if(root->next[b] == NULL){
root->next[b] = create();
}
root = root->next[b];
++root->v;
}
}
int search(trie *root, char *s){
while(*s){
int b = *s - 'a';
++s;
if(root->next[b] == NULL){
return 0;
}
root = root->next[b];
}
return root->v;
}