求条玄关
查看原帖
求条玄关
1277996
mc2djwh楼主2025/7/29 21:11
#include <bits/stdc++.h>
using namespace std;
string s;
string t[200010];
struct node {
	char c;
	int fail;
	int next[26];
	vector<string> e;
	int fa;
};
node trie[200010];
const int root = 0;
int cnt = 1, n;
map<string, int> ans;
void insert(string s) {
	int p = root;
	for (int i = 0; i < s.length(); i++) {
		int idx = s[i] - 'a';
		if (!trie[p].next[idx]) trie[p].next[idx] = cnt++;
		trie[trie[p].next[idx]].fa = p;
		p = trie[p].next[idx];
		trie[p].c = s[i];
	}
	trie[p].e.push_back(s);
}
void build_fail() {
	queue<int> q;
	q.push(root);
	trie[root].fail = root;
	while (!q.empty()) {
		int p = q.front();
		q.pop();
		if (trie[p].fa != -1) {
			for (int i = 0; i < 26; i++) {
				if (trie[trie[trie[trie[p].fa].fail].next[i]].c == trie[p].c) {
					trie[p].fail = trie[trie[trie[p].fa].fail].next[i];
					if (trie[trie[trie[trie[p].fa].fail].next[i]].e.size()) {
						for (string j : trie[trie[trie[trie[p].fa].fail].next[i]].e) {
							trie[p].e.push_back(j);
						}
					}
				}
				else {
					trie[p].fail = root;
				}
			}
		}
	}
}
void search() {
	int p = root;
	for (int i = 0; i < s.size(); i++) {
		int idx = s[i] - 'a';
		for (string k : trie[p].e) {
			ans[k]++;
		}
		while (p != root && trie[p].c != s[i]) {
			p = trie[p].fail;
		}
		p = trie[p].next[idx];
	}
}
signed main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> t[i];
		insert(t[i]);
	}
	build_fail();
	cin >> s;
	trie[root].fa = -1;
	search();
	for (int i = 1; i <= n; i++) {
		cout << ans[t[i]] << endl;
	}
	return 0;
}
2025/7/29 21:11
加载中...