結果

問題 No.430 文字列検索
ユーザー sykwersykwer
提出日時 2019-08-21 15:40:10
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,644 bytes
コンパイル時間 749 ms
コンパイル使用メモリ 70,136 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-17 10:02:52
合計ジャッジ時間 18,176 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 863 ms
5,376 KB
testcase_02 AC 1,297 ms
5,376 KB
testcase_03 AC 1,029 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 6 ms
5,376 KB
testcase_09 AC 3 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,355 ms
5,376 KB
testcase_17 AC 1,294 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

using namespace std;

// O(|S|)
vector<int> z_algorithm(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();

        pattern.append("$");
        pattern.append(str);

        vector<int> z_array = z_algorithm(pattern);

        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