字典树/前缀树

发布于:2025-08-01 ⋅ 阅读:(16) ⋅ 点赞:(0)

Solution

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int max_n = 1e6 + 5;
int tree[max_n][26];
int Pass[max_n];
int End[max_n];
int cnt = 1;
void insert(string word) {
	int node = 1;//从根节点开始
	Pass[node]++;
	for (int i = 0; i < word.length(); ++i) {
		int path = word[i] - 'a';
		if (tree[node][path] == 0) {
			tree[node][path] = ++cnt;
		}
		node = tree[node][path];
		Pass[node]++;
	}
	End[node]++;
}
int countWord(string word) {
	int node = 1;
	for (int i = 0; i < word.length(); ++i) {
		int path = word[i] - 'a';
		if (tree[node][path] == 0) return 0;
		node = tree[node][path];
	}
	return End[node];
}
int countPre(string pre) {
	int node = 1;
	for (int i = 0; i < pre.length(); ++i) {
		int path = pre[i] - 'a';
		if (tree[node][path] == 0) return 0;
		node = tree[node][path];
	}
	return Pass[node];
}
void delete_word(string word) {
	int node = 1;
	if (countWord(word) > 0) {
		for (int i = 0; i < word.length(); ++i) {
			int path = word[i] - 'a';
			if (--Pass[tree[node][path]] == 0) {//这里注意减的是哪个节点的Pass值
				tree[node][path] = 0;
				return;
			}
			node = tree[node][path];
		}
		End[node]--;
	}
}

void clear() {
	// 清空整个 tree 数组
	memset(tree, 0, sizeof(tree));
	// 清空 Pass 数组
	memset(Pass, 0, sizeof(Pass));
	// 清空 End 数组
	memset(End, 0, sizeof(End));
	// 重置节点计数
	cnt = 1;
}
int main() {
	insert("Fan");
	insert("Fang");
	insert("Fantasy");
	cout << countWord("Fan") << endl;
	cout << countPre("Fa") << endl;
	delete_word("Fan");
	cout << countWord("Fan") << endl;
	cout << countPre("Fan") << endl;

	
	return 0;
}

网站公告

今日签到

点亮在社区的每一天
去签到