結果

問題 No.430 文字列検索
ユーザー legosuke
提出日時 2021-11-12 21:43:46
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
実行時間 -
コード長 1,815 bytes
コンパイル時間 1,988 ms
コンパイル使用メモリ 197,204 KB
最終ジャッジ日時 2025-01-25 16:13:29
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 4 TLE * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

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

int64_t random_number(int64_t n) {
    mt19937_64 mt(std::chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<int64_t> dist(0, n - 1);
    return dist(mt);
}

const int64_t MOD = ((int64_t)1 << 61) - 1;
const int64_t MASK30 = ((int64_t)1 << 30) - 1;
const int64_t MASK31 = ((int64_t)1 << 31) - 1;
const int64_t MASK61 = ((int64_t)1 << 61) - 1;
int64_t base = random_number(MOD);

int64_t mod(int64_t x) {
    int64_t res = (x >> 61) + (x & MASK61);
    if (res >= MOD) res -= MOD;
    return res;
}

int64_t mul(int64_t a, int64_t b) {
    int64_t au = (a >> 31), ad = (a & MASK31);
    int64_t bu = (b >> 31), bd = (b & MASK31);
    int64_t c = (au * bd + ad * bu);
    int64_t cu = (c >> 30), cd = (c & MASK30);
    return mod(au * bu * 2 + cu + (cd << 31) + ad * bd);
}

int64_t add(int64_t a, int64_t b) {
    return mod(a + b);
}

int64_t sub(int64_t a, int64_t b) {
    int64_t res = a - b;
    if (res < 0) res += MOD;
    return res;
}

vector<int> pattern_matching(const string& a, const string& b) {
    int az = a.size(), bz = b.size();
    if (az > bz) return vector<int>();
    int64_t ah = 0, bh = 0, t = 1;
    for (int i = 0; i < az; ++i) {
        ah = add(mul(ah, base), a[i]);
        bh = add(mul(bh, base), b[i]);
        t = mul(t, base);
    }
    vector<int> pos;
    for (int i = 0; i + az <= bz; ++i) {
        if (ah == bh) pos.push_back(i);
        if (i + az < bz) bh = sub(add(mul(bh, base), b[i + az]), mul(b[i], t));
    }
    return pos;
}

int main() {
    string S;
    int M;
    cin >> S >> M;
    int ans = 0;
    for (int i = 0; i < M; ++i) {
        string C;
        cin >> C;
        auto pos = pattern_matching(C, S);
        ans += pos.size();
    }
    cout << ans << endl;
    return 0;
}
0