字典樹

利用公共前綴減少查詢時間,節省內存

靜態分配,動態分配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;
}


發佈了102 篇原創文章 · 獲贊 3 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章