結果

問題 No.430 文字列検索
コンテスト
ユーザー shinchan
提出日時 2025-10-29 17:51:33
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 14 ms / 2,000 ms
コード長 2,302 bytes
コンパイル時間 2,197 ms
コンパイル使用メモリ 215,884 KB
実行使用メモリ 7,716 KB
最終ジャッジ日時 2025-10-29 17:51:37
合計ジャッジ時間 3,557 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 14
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

struct Aho{
  const int a = 'A';
  vector<array<int, 26>> nx;
  vector<int> fail;
  vector<vector<int>> accept;
  vector<int> correct;
  int node_count;
  Aho() {
    node_count = 1;
    nx.assign(1, {});
    for (auto &a : nx[0]) a = -1;
    fail.assign(1, 0);
    accept.resize(1);
  }
  void add(const string &s, int id = -1) {
    int node = 0;
    for (char ch : s) {
      int c = ch - a;
      if (nx[node][c] == -1) {
        nx[node][c] = node_count++;
        nx.push_back({});
        for (auto &c : nx.back()) c = -1;
        fail.push_back(0);
        accept.push_back({});
      }
      node = nx[node][c];
    }
    accept[node].push_back(id);
  }
  void build(bool heavy = true) {
    correct.assign(node_count, 0);
    for (int i = 0; i < node_count; i++) correct[i] = (int)accept[i].size();
    queue<int> q;
    for (int c = 0; c < 26; c++) {
      int nxt = nx[0][c];
      if (nxt != -1) {
        fail[nxt] = 0;
        q.push(nxt);
      } else {
        nx[0][c] = 0;
      }
    }
    while (!q.empty()) {
      int v = q.front(); q.pop();
      int f = fail[v];
      correct[v] += correct[f];

      for (int c = 0; c < 26; c++) {
        int u = nx[v][c];
        if (u != -1) {
          fail[u] = nx[f][c];
          if (heavy) {
            auto &A = accept[u];
            auto &B = accept[fail[u]];
            for (int id : B) A.push_back(id);
            sort(A.begin(), A.end());
            A.erase(unique(A.begin(), A.end()), A.end());
          }
          q.push(u);
        } else {
          nx[v][c] = nx[f][c];
        }
      }
    }
  }
  vector<int> match(const char &c, int now = 0) const {
    now = nx[now][c - a];
    return accept[now];
  }
  pair<ll, int> move(const char &c, int now = 0) const {
    now = nx[now][c - a];
    return {correct[now], now};
  }
};


void solve() {
  string S;
  cin >> S;
  int M;
  cin >> M;
  Aho aho;
  for (int i = 0; i < M; i++) {
    string s; cin >> s;
    aho.add(s, i);
  }
  aho.build();

  ll sum = 0;
  int now = 0;
  for(char e: S) {
    sum += aho.match(e, now).size();
    auto [cnt, nx] = aho.move(e, now);
    now = nx;
    
  }
  cout << sum << endl;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  solve();
}
0