Cod sursa(job #2723187)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 13 martie 2021 19:03:20
Problema Aho-Corasick Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <bits/stdc++.h>

using namespace std;

string s;

struct node {
  node* k[26];
  node* to;
  vector<int> ind;
  int cnt;
  node() {
    for (int j = 0; j < 26; j++) {
      k[j] = 0;
    }
    cnt = 0;
    to = 0;
  }
};

node* root = new node;

vector<node*> ord;

void bfs() {
  queue<node*> q;
  q.push(root);
  while (!q.empty()) {
    node *now = q.front();
    ord.push_back(now);
    q.pop();
    for (int j = 0; j < 26; j++) {
      if (now->k[j]) {
        q.push(now->k[j]);
      }
    }
  }
}

void build(vector<string> v) {
  int y = (int) v.size();
  int pz = 0;
  for (auto &s : v) {
    node* now = root;
    for (auto &ch : s) {
      int x = ch - 'a';
      if (!now->k[x]) {
        now->k[x] = new node;
      }
      now = now->k[x];
    }
    now->ind.push_back(pz++);
  }
  bfs();
  root->to = root;
  for (auto &now : ord) {
    for (int j = 0; j < 26; j++) {
      if (now->k[j]) {
        node* sol = now->to;
        while (sol != root && !sol->k[j]) {
          sol = sol->to;
        }
        if (now != root && sol->k[j]) {
          sol = sol->k[j];
        }
        now->k[j]->to = sol;
      }
    }
  }
  node* state = root;
  for (auto &ch : s) {
    int x = ch - 'a';
    while (state != root && !state->k[x]) {
      state = state->to;
    }
    if (state->k[x]) {
      state = state->k[x];
    }
    state->cnt++;
  }
  reverse(ord.begin(), ord.end());
  vector<int> sol(y);
  for (auto &now : ord) {
    now->to->cnt += now->cnt;
    for (auto &i : now->ind) {
      sol[i] = now->cnt;
    }
  }
  for (auto &x : sol) {
    cout << x << "\n";
  }
}

int main() {
  freopen ("ahocorasick.in", "r", stdin);
  //freopen ("ahocorasick.out", "w", stdout);

  cin >> s;
  int len;
  cin >> len;
  vector<string> v(len);
  for (auto &x : v) {
    cin >> x;
  }
  build(v);

}