結果

問題 No.430 文字列検索
ユーザー sykwersykwer
提出日時 2019-08-21 15:45:53
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,661 bytes
コンパイル時間 806 ms
コンパイル使用メモリ 70,428 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-17 10:49:13
合計ジャッジ時間 19,165 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 1,059 ms
5,376 KB
testcase_02 AC 1,382 ms
5,376 KB
testcase_03 AC 1,065 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 2 ms
5,376 KB
testcase_08 AC 7 ms
5,376 KB
testcase_09 AC 2 ms
5,376 KB
testcase_10 AC 4 ms
5,376 KB
testcase_11 TLE -
testcase_12 TLE -
testcase_13 TLE -
testcase_14 TLE -
testcase_15 TLE -
testcase_16 AC 1,382 ms
5,376 KB
testcase_17 AC 1,337 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// O(|S|)
vector<int> z_algorithm(const string &S) {
    auto N = (int) S.size();

    // Z-Array
    vector<int> Z(N);
    Z[0] = N;

    /* For the already computed prefixes S[0..len-1] == S[idx..idx+len-1]
     * r = max(idx+len-1)
     * l = such i that maximizes (idx+len-1)
     */
    int l = -1;
    int r = -1;

    for (int k = 1; k < N; k++) {
        int p = k - l;

        if (k > r) {
            for (int i = k; i <= N; i++) {
                if (i == N || S[i-k] != S[i]) {
                    Z[k] = i-k;
                    l = k;
                    r = i-1;
                    break;
                }
            }
        } else if (Z[p] < r-k+1) {
            Z[k] = Z[p];
        } else { // Z[p] >= r-k+1
            for (int i = r+1; i <= N; i++) {
                if (i == N || S[i-k] != S[i]) {
                    Z[k] = i-k;
                    l = k;
                    r = i-1;
                    break;
                }
            }
        }
    }

    return move(Z);
}

// Verified at https://yukicoder.me/problems/no/430
int main() {
    string str;
    int Q;
    cin >> str >> Q;

    int ret = 0;

    for (int i = 0; i < Q; i++) {
        string pattern;
        cin >> pattern;
        auto M = (int) pattern.size();

        string T;
        T += pattern;
        T += "$";
        T += str;
        vector<int> z_array = z_algorithm(T);

        int cnt = 0;
        for (int j = M + 1; j < z_array.size(); j++) {
            if (z_array[j] == M) cnt++;
        }
        ret += cnt;
    }

    cout << ret << endl;
    return 0;
}
0