結果

問題 No.430 文字列検索
ユーザー kyo1
提出日時 2020-06-04 15:38:08
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,046 ms / 2,000 ms
コード長 2,380 bytes
コンパイル時間 3,610 ms
コンパイル使用メモリ 196,336 KB
最終ジャッジ日時 2025-01-10 21:13:30
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 14
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

class Random {
 private:
  static inline std::mt19937_64 mt{static_cast<uint64_t>(
      std::chrono::steady_clock::now().time_since_epoch().count())};

 public:
  template <typename T>
  static T random(T hi) {
    std::uniform_int_distribution<T> uid(0, hi - 1);
    return uid(mt);
  }

  template <typename T>
  static T random(T lo, T hi) {
    std::uniform_int_distribution<T> uid(lo, hi - 1);
    return uid(mt);
  }
};

class RollingHash {
 private:
  const uint64_t mod = (UINT64_C(1) << 61) - 1;
  static inline uint64_t base =
      Random::random(UINT64_C(10007), UINT64_C(1) << 28);
  std::vector<uint64_t> hashes, pows;

  uint64_t add(uint64_t a, uint64_t b) const {
    a += b;
    if (a >= mod) a -= mod;
    return a;
  }

  uint64_t sub(uint64_t a, uint64_t b) const {
    if (a < b) a += mod;
    a -= b;
    return a;
  }

  uint64_t mul(uint64_t a, uint64_t b) const {
    uint64_t ah = a >> 31, al = a & ((UINT64_C(1) << 31) - 1), bh = b >> 31,
             bl = b & ((UINT64_C(1) << 31) - 1), m = ah * bl + al * bh,
             v = (ah * bh << 1) + (m >> 30) +
                 ((m & ((UINT64_C(1) << 30) - 1)) << 31) + al * bl;
    v = (v & ((UINT64_C(1) << 61) - 1)) + (v >> 61);
    return v;
  }

 public:
  template <typename T>
  RollingHash(const T &S) : hashes(S.size() + 1, 0), pows(S.size() + 1, 0) {
    pows[0] = 1;
    for (size_t i = 0; i < S.size(); i++) {
      pows[i + 1] = mul(pows[i], base);
      hashes[i + 1] = add(mul(hashes[i], base), S[i]);
    }
  }

  template <typename T>
  RollingHash(const T &S, const uint64_t base)
      : hashes(S.size() + 1, 0), pows(S.size() + 1, 0) {
    pows[0] = 1;
    for (size_t i = 0; i < S.size(); i++) {
      pows[i + 1] = mul(pows[i], base);
      hashes[i + 1] = add(mul(hashes[i], base), S[i]);
    }
  }

  // S[l, r)
  uint64_t slice(int l, int r) const {
    return sub(hashes[r], mul(hashes[l], pows[r - l]));
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  string S;
  cin >> S;
  int M;
  cin >> M;
  RollingHash rhs(S);
  int res = 0;
  for (int i = 0; i < M; i++) {
    string C;
    cin >> C;
    RollingHash rhc(C);
    for (int j = 0; j + (int)C.size() < (int)S.size() + 1; j++) {
      if (rhs.slice(j, j + (int)C.size()) == rhc.slice(0, (int)C.size())) res++;
    }
  }
  cout << res << '\n';
  return 0;
}
0