結果

問題 No.430 文字列検索
ユーザー kyo1kyo1
提出日時 2020-09-16 06:18:54
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 864 ms / 2,000 ms
コード長 1,968 bytes
コンパイル時間 1,969 ms
コンパイル使用メモリ 203,592 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 03:20:09
合計ジャッジ時間 11,526 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 859 ms
4,376 KB
testcase_02 AC 858 ms
4,380 KB
testcase_03 AC 864 ms
4,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 6 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 4 ms
4,380 KB
testcase_11 AC 861 ms
4,380 KB
testcase_12 AC 860 ms
4,376 KB
testcase_13 AC 860 ms
4,376 KB
testcase_14 AC 859 ms
4,376 KB
testcase_15 AC 859 ms
4,380 KB
testcase_16 AC 858 ms
4,380 KB
testcase_17 AC 858 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

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

  constexpr static std::uint64_t mod = (UINT64_C(1) << 61) - 1;
  static inline std::uint64_t base = random(UINT64_C(10007), UINT64_C(1) << 28);
  std::vector<std::uint64_t> powers;
  std::vector<std::uint64_t> hashes;

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

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

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

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

  std::uint64_t query(const std::size_t l, const std::size_t r) const {
    return sub(hashes[r], mul(hashes[l], powers[r - l]));
  }
};

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