[模板 | C++] Trie(字典树、前缀树)

URL:P8306 【模板】字典树 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include "bits/stdc++.h"

struct trie {
	int pass, end;
	std::unordered_map <char, int> next;

	trie() {
		pass = 0;
		end = 0;
	}

};

int num = 0;

void insert(std::string s, std::vector <trie> &tr) {
	for (int i = 0, o = 0; i < s.length(); ++ i) {
		if (!tr[o].next.count(s[i])) {
			tr[o].next[s[i]] = ++ num;
		}
		o = tr[o].next[s[i]]; // 先移动到当前si代表的点

		tr[o].pass ++;
		if (i == s.length() - 1) tr[o].end ++;

		//std::cout << "pass = " << tr[o].pass << "\n";
	}
}

int query(std::string s, std::vector <trie> &tr) {
	for (int i = 0, o = 0; i < s.length(); ++ i) {
		if (!tr[o].next.count(s[i])) return 0;
		
		o = tr[o].next[s[i]];

		if (i == s.length() - 1) return tr[o].pass; 
	}

}

signed main() {
	int t; std::cin >> t;

	while (t --) {
		int n, q; std::cin >> n >> q;

		num = 0;

		int sum = 0;
		std::vector <std::string> tmp;

		for (int i = 1; i <= n; ++ i) {
			std::string s; std::cin >> s;
			tmp.push_back(s);
			sum += s.length();
		}

		std::vector <trie> tr(sum << 1);
		for (auto &s : tmp) {
			insert(s, tr);
		}

		for (int i = 1; i <= q; ++ i) {
			std::string s; std::cin >> s;
			std::cout << query(s, tr) << "\n";
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值