Cod sursa(job #3348514)

Utilizator matei0000Neacsu Matei matei0000 Data 22 martie 2026 13:51:03
Problema Aho-Corasick Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

const int K = 26;

struct AHO {
	int nr = 0;
	struct Node {
		int p = 0;
		vector<int> nxt, out;
		Node() {
			nxt.assign(K, -1);
		}
	};
	vector<Node> trie;
	AHO() {
		trie.emplace_back();
	}
	void add(string s) {
		int pos = 0;
		for (auto i : s) {
			i = i - 'a';
			if (trie[pos].nxt[i] == -1) {
				trie[pos].nxt[i] = trie.size();
				trie.emplace_back();
			}
			pos = trie[pos].nxt[i];
		}
		trie[pos].out.push_back(nr ++);
	}
	void build() {
		queue<int> q;
		for (int c = 0; c < K; c ++) {
			if (trie[0].nxt[c] != -1) {
				trie[trie[0].nxt[c]].p = 0;
				q.push(trie[0].nxt[c]);
			} else {
				trie[0].nxt[c] = 0;
			}
		}
		while (!q.empty()) {
			auto x = q.front();
			q.pop();
			for (int c = 0; c < K; c ++) {
				int v = trie[x].nxt[c];
				if (v != -1) {
					trie[v].p = trie[trie[x].p].nxt[c];
					for (auto j : trie[trie[v].p].out) {
						trie[v].out.push_back(j);
					}
					q.push(v);
				} else {
					trie[x].nxt[c] = trie[trie[x].p].nxt[c];
				}
			}
		}
	}
	vector<int> query(string s) {
		int pos = 0;
		vector<int> ans(nr);
		for (auto i : s) {
			i = i - 'a';
			pos = trie[pos].nxt[i];
			for (auto j : trie[pos].out) {
				ans[j] ++;
			}
		}
		return ans;
	}
};

signed main() {
	ifstream cin("ahocorasick.in");
	ofstream cout("ahocorasick.out");
	int n;
	string a;
	cin >> a >> n;
	vector<string> s(n);
	for (auto &i : s) {
		cin >> i;
	}
	AHO ds;
	for (auto i : s) {
		ds.add(i);
	}
	ds.build();
	auto x = ds.query(a);
	for (auto i : x) {
		cout << i << " ";
	}
	cout << '\n';
}