結果

問題 No.430 文字列検索
ユーザー aisuaisu
提出日時 2023-02-21 10:09:30
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 485 ms / 2,000 ms
コード長 922 bytes
コンパイル時間 656 ms
コンパイル使用メモリ 74,856 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-29 04:23:29
合計ジャッジ時間 6,372 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <vector>
using namespace std;

#define B1 100000007
#define B2 1000000007

int rolling_hash(string S, string c)
{
    int ans=0;

    unsigned long long pow_B1=1, pow_B2=1;
    for(int k=0; k<c.length(); k++)
        pow_B1*=B1, pow_B2*=B2;

    unsigned long long ch1=0, ch2=0, sh1=0, sh2=0;
    for(int k=0; k<c.length(); k++)
    {
        ch1=ch1*B1+c[k]; ch2=ch2*B2+c[k];
        sh1=sh1*B1+S[k]; sh2=sh2*B2+S[k];
    }

    for(int k=0; k+c.length()<=S.length(); k++)
    {
        if(ch1==sh1&&ch2==sh2) ans++;
        sh1=sh1*B1+S[k+c.length()]-S[k]*pow_B1;
        sh2=sh2*B2+S[k+c.length()]-S[k]*pow_B2;
    }
    return ans;
}

int main()
{
    string S; cin >> S;
    int M; cin >> M;
    vector<string> C(M);
    for(int i=0; i<M; i++)
        cin >> C[i];
    
    int ans=0;
    for(int i=0; i<M; i++)
        ans+=rolling_hash(S, C[i]);
    cout << ans << '\n';
    return 0;
}
0