蒟蒻求助,被卡常卡吐了
查看原帖
蒟蒻求助,被卡常卡吐了
928879
stripe_python楼主2023/8/19 08:58

用的是自己的 Trie 模板,TLE on #3, 4, 5,已经试过各位大佬的方法,改了 memset,但还是 T,没有改 cin/cout (说好的不卡常),求调

#include <bits/stdc++.h>
#define N 3000005
#define M 65
using namespace std;

int t, n, q;
string s;

class Trie {
protected:
	function<int(char)> mapping;
	int t[N][M], cnt[N];
	int tot;

public:
	Trie() : tot(0) {
		mapping = [](char x) -> int {
			if ('A' <= x && x <= 'Z') return x - 'A';
			else if ('a' <= x && x <= 'z') return x - 'a' + 26;
			else return x - '0' + 52;
		};
	}
	
	Trie(function<int(char)>& func) : tot(0) {
		mapping = func;
	}
	
	void clear() {
		memset(t, 0, sizeof(t[0]) * tot);
		memset(cnt, 0, sizeof(int) * tot);
	}
	
	void insert(const string& s) {
		int p = 0, n = (int) s.size();
		for (int i = 0; i < n; i++) {
			int c = mapping(s[i]);
			if (!t[p][c]) t[p][c] = ++tot;
			p = t[p][c];
			cnt[p]++;
		}
	}
	
	int find(const string& s) {
		int p = 0, n = (int) s.size();
		for (int i = 0; i < n; i++) {
			int c = mapping(s[i]);
			if (!t[p][c]) return 0;
			p = t[p][c];
		}
		return cnt[p];
	}
};

Trie trie;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr), cout.tie(nullptr);
	cin >> t;
	while (t--) {
		trie.clear();
		cin >> n >> q;
		while (n--) {
			cin >> s;
			trie.insert(s);
		}
		while (q--) {
			cin >> s;
			cout << trie.find(s) << '\n';
		}
	}
	return 0;
}

2023/8/19 08:58
加载中...