跳到正文

个人记录

关于 Trie

FLY_lai约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年1月2日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

【Trie 是什么】

Trie,字典树,存储字符串的树形结构。

【Trie 的作用】

Trie 可以高效地查询一个字符串出现的次数。

【Trie 的实现】

Trie 包含:

  1. 布尔数组 tr,其中 tr[i][j]=truetr[i][j]=true 表示 ii 号结点有 jj 号字符的儿子。

  2. 数组 cntcnt,cnt[i]cnt[i] 记录 以 ii 号结点结尾的字符串个数。

初始只有一个根节点。

每插入一个字符串,都把它的字符遍历一遍。

当遍历到字符 sis_i 时,看看当前结点 uu 是否有 sis_i 这个儿子。

若有,ii 后移一位,uu 变为这个儿子;

否则给 uu 新建一个儿子表示 sis_i,再切换到这个儿子上。

遍历结束后,给最后结点的 cntcnt 值加一。


查询进行类似操作,每次看看当前结点有没有对应字符的儿子。

若有,切换到这个儿子上;

若没有,说明没有这个字符串。

遍历结束后,返回当前结点的 cntcnt 值。

显然时间复杂度是 O(O(层数))。

【Code】

板子题:P2580 于是他错误的点名开始了

C++
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

int n;
char s[60];

int tot = 0;
int tr[1000005][50];
int ed[1000005] = {};
int fnd[1000005] = {};

void add(char *s) {
	int len = strlen(s);
	int u = 1;
	for (int i = 0; i < len; i++) {
		int c = s[i] - 'a';
		if (!tr[u][c])
			tr[u][c] = ++tot;
		u = tr[u][c];
	}
	ed[u]++;
}

int query(char *s) {
	int len = strlen(s), u = 1;
	for (int i = 0; i < len; i++) {
		int c = s[i] - 'a';
		if (tr[u][c] == 0)
			return 0;
		u = tr[u][c];
	}
	if (fnd[u])
		return 1;
	fnd[u]++;
	return 2;
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		scanf("%s", &s);
		add(s);
	}
	int m;
	cin >> m;
	for (int i = 1; i <= m; i++) {
		scanf("%s", s);
		int tmp = query(s);
		if (tmp == 0)
			cout << "WRONG" << endl;
		else if (tmp == 1)
			cout << "REPEAT" << endl;
		else
			cout << "OK" << endl;
	}
	return 0;
}
原文