結果

問題 No.430 文字列検索
ユーザー Kiona1018
提出日時 2019-10-10 23:36:30
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,972 ms / 2,000 ms
コード長 1,329 bytes
コンパイル時間 1,328 ms
コンパイル使用メモリ 169,444 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-11-10 00:36:16
合計ジャッジ時間 15,468 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 14
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
#define rep(i,n,m) for(int i = (n); i <(m); i++)
#define rrep(i,n,m) for(int i = (n) - 1; i >=(m); i--)
using namespace std;
using ll = long long;

int kmp_search(string ref, string key)
{
    vector<int> index(key.size(), 0);
    int i, j;
    i = 0, j = 1;
    while (j < key.size())
    {
        if (key[i] == key[j])
        {
            ++i;
            index[j] = i;
            ++j;
        }
        else if (i == 0)
        {
            index[j] = 0;
            ++j;
        }
        else
            i = index[i-1];
        // cout << "a : " << i << ' ' << j << ' ' << key << endl;
    }

    i = j = 0;
    int cnt = 0;
    while (i < ref.size())
    {
        if (ref[i] == key[j])
            ++i, ++j;
        else if (j == 0)
            ++i;
        else
            j = index[j-1];
        
        if (j == key.size())
            ++cnt, j = index[j-1];
        // cout << "b : " << i << ' ' << j << ' ' << key << endl;
    }
    // cout << cnt << endl;
    return cnt;
}

int main()
{
    std::ios_base::sync_with_stdio(false);
    string s;
    int m;
    cin >> s >> m;
    int cnt = 0;
    rep(i, 0, m)
    {
        string key;
        cin >> key;

        cnt += kmp_search(s, key);
        // cout << kmp_search(s, key) << endl;
    }
    cout << cnt << endl;
    return 0;
}
0