跳到正文

剪贴板

剪贴板 nwmgm66l

原文
剪贴板信息

剪贴板信息

收录
更新
C++
namespace trie {
	struct Node {
		int cnt;
		// 包含该结点已插入的字符串的数量

		Node* child[70];
		// 子节点
	};

	Node t[N];
	int ts;

	void init() {
		ts=0;
	}

	// 分配一个新的结点
	Node* load() {
		t[++ts]= {0,{}};
		return t+ts;
	}

	// 将字符映射为数字
	int map_char(char c) {
		if(c>='a'&&c<='z') {
			return c-'a';
		} else if(c>='A'&&c<='Z') {
			return c-'A'+26;
		} else {
			return c-'0'+52;
		}
	}

	// 插入一个字符串
	void insert(Node* root,const string& s) {
		Node* current=root;
		for(char c:s) {
			int x=map_char(c);
			if(!current->child[x]) {
				current->child[x]=load();
			}
			current=current->child[x];
			current->cnt++;
		}
	}

	// 查询一个字符串作为前缀的次数
	int query(Node* root,const string& s) {
		Node* current=root;
		for(char c:s) {
			int x=map_char(c);
			if(current->child[x]) {
				current=current->child[x];
			} else {
				return 0;
			}
		}
		return current->cnt;
	}
}