Cod sursa(job #3376980)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 20 noiembrie 2026 20:12:00
Problema Aho-Corasick Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <bits/stdc++.h>
using namespace std;

struct AhoCorasick {
    struct Node { int head = -1, link = 0, cnt = 0; };
    struct Edge { int to, next, c; };
    vector<Node> t;
    vector<Edge> e;
    vector<int> end, order;
    AhoCorasick(int total = 0) {
        t.reserve(total + 1);
        e.reserve(total);
        t.emplace_back();
    }
    int go(int u, int c) const {
        for (int i = t[u].head; i != -1; i = e[i].next)
            if (e[i].c == c) return e[i].to;
        return -1;
    }
    void add(const string &s) {
        int u = 0;
        for (char ch : s) {
            int c = ch - 'a', v = go(u, c);
            if (v == -1) {
                v = t.size();
                t.emplace_back();
                e.push_back({v, t[u].head, c});
                t[u].head = (int)e.size() - 1;
            }
            u = v;
        }
        end.push_back(u);
    }
    void build() {
        order.clear();
        order.reserve(t.size());
        for (int i = t[0].head; i != -1; i = e[i].next)
            order.push_back(e[i].to);
        for (int i = 0; i < (int)order.size(); i++) {
            int u = order[i];
            for (int j = t[u].head; j != -1; j = e[j].next) {
                int v = e[j].to, c = e[j].c;
                int p = t[u].link;
                while (p && go(p, c) == -1) p = t[p].link;
                int w = go(p, c);
                t[v].link = w == -1 ? 0 : w;
                order.push_back(v);
            }
        }
    }
    void run(const string &s) {
        for (auto &v : t) v.cnt = 0;
        int u = 0;
        for (char ch : s) {
            int c = ch - 'a', v = go(u, c);
            while (v == -1 && u) {
                u = t[u].link;
                v = go(u, c);
            }
            u = v == -1 ? 0 : v;
            t[u].cnt++;
        }
        for (int i = (int)order.size() - 1; i >= 0; i--) {
            int v = order[i];
            t[t[v].link].cnt += t[v].cnt;
        }
    }
    int count(int i) const { return t[end[i]].cnt; }
};

int main() {
    ifstream fin("ahocorasick.in");
    ofstream fout("ahocorasick.out");

    string s;
    int n, total = 0;
    fin >> s >> n;
    vector<string> a(n);
    for (string &x : a) {
        fin >> x;
        total += x.size();
    }
    AhoCorasick d(total);
    for (const string &x : a) d.add(x);
    d.build();
    d.run(s);
    for (int i = 0; i < n; i++) fout << d.count(i) << '\n';
}