蒟蒻求助,trie树52分
查看原帖
蒟蒻求助,trie树52分
592342
WA_automat楼主2022/7/18 15:03

不知道是不是被卡常数了 TLE了两个点

#include<iostream>
#include<string>
using namespace std;
const int N = 3e6 + 1;
int t, n, q, son[N][62], cnt[N], idx;
string str;
inline int getnum(char x) {
	if (x >= 'A' && x <= 'Z')
		return x - 'A';
	else if (x >= 'a' && x <= 'z')
		return x - 'a' + 26;
	else
		return x - '0' + 52;
}
inline void insert(const char* str) {
	int p = 0;
	for (register int i = 0; str[i]; ++i) {
		int u = getnum(str[i]);
		if (!son[p][u]) son[p][u] = ++idx;
		p = son[p][u];
		++cnt[p];
	}
}
int query(const char* str) {
	int p = 0;
	for (register int i = 0; str[i]; i++)
	{
		int u = getnum(str[i]);
		if (!son[p][u]) return 0;
		p = son[p][u];
	}
	return cnt[p];
}
int main(void) {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> t;
	while (t--) {
		for (register int i = 0; i <= idx; i++)
			for (int j = 0; j <= 62; j++)
				son[i][j] = 0;
		for (register int i = 0; i <= idx; i++)
			cnt[i] = 0;
		cin >> n >> q;
		while (n--) {
			cin >> str;
			insert(str.c_str());
		}
		while (q--) {
			cin >> str;
			cout << query(str.c_str()) << '\n';
		}
	}
	return 0;
}
2022/7/18 15:03
加载中...