結果

問題 No.430 文字列検索
ユーザー kyo1kyo1
提出日時 2020-01-27 12:52:30
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 834 ms / 2,000 ms
コード長 1,534 bytes
コンパイル時間 1,609 ms
コンパイル使用メモリ 168,124 KB
実行使用メモリ 4,356 KB
最終ジャッジ日時 2023-10-12 12:55:02
合計ジャッジ時間 11,040 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

class RollingHash {
 private:
  using u64 = std::uint_fast64_t;

  const u64 mod = (1ULL << 61) - 1;
  std::vector<u64> hashes, pows;

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

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

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

 public:
  RollingHash(const std::string &S, u64 base = 10007)
      : hashes((int)S.size() + 1, 0), pows((int)S.size() + 1, 0) {
    int sz = (int)S.size();
    pows[0] = 1;
    for (int i = 0; i < sz; i++) {
      pows[i + 1] = mul(pows[i], base);
      hashes[i + 1] = add(mul(hashes[i], base), S[i]);
    }
  }

  u64 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;
  RollingHash rhs(S);
  int M;
  cin >> M;
  int res = 0;
  for (int i = 0; i < M; i++) {
    string C;
    cin >> C;
    RollingHash rhc(C);
    for (int i = 0; i + (int)C.size() < (int)S.size() + 1; i++) {
      if (rhs.slice(i, i + (int)C.size()) == rhc.slice(0, (int)C.size())) res++;
    }
  }
  cout << res << '\n';
  return 0;
}
0