結果

問題 No.1005 BOT対策
コンテスト
ユーザー Dashcoding
提出日時 2026-03-27 21:33:31
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 3 ms / 2,000 ms
コード長 2,252 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,567 ms
コンパイル使用メモリ 178,968 KB
実行使用メモリ 6,272 KB
最終ジャッジ日時 2026-03-27 21:33:38
合計ジャッジ時間 3,527 ms
ジャッジサーバーID
(参考情報)
judge2_0 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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

vector<int> compute_next(const string& t) {
    int m = t.size();
    vector<int> next(m, -1);
    int j = -1;
    for (int i = 1; i < m; ++i) {
        while (j != -1 && t[i] != t[j+1]) {
            j = next[j];
        }
        if (t[i] == t[j+1]) {
            j++;
        }
        next[i] = j;
    }
    return next;
}

void build_trans(const string& t, const vector<int>& next, vector<vector<int>>& trans) {
    int m = t.size();
    trans.resize(m + 1, vector<int>(26));
    for (int j = 0; j <= m; ++j) {
        for (char c = 'a'; c <= 'z'; ++c) {
            int cur = j;
            while (cur > 0) {
                if (t[cur] == c) break;
                cur = next[cur - 1] + 1;
            }
            if (cur < m && t[cur] == c) {
                cur++;
            }
            trans[j][c - 'a'] = cur;
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string S, T;
    cin >> S >> T;
    int n = S.size();
    int m = T.size();

    if (m > n) {
        cout << 0 << endl;
        return 0;
    }

    vector<int> next = compute_next(T);
    vector<vector<int>> trans;
    build_trans(T, next, trans);

    const int INF = 1e9;
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, INF));
    dp[0][0] = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j <= m; ++j) {
            if (dp[i][j] == INF) continue;
            char c = S[i];
            // 选项1:插入'.',先处理'.'(匹配重置为0),再处理当前字符
            int nj_insert = trans[0][c - 'a'];
            if (nj_insert != m) {
                dp[i + 1][nj_insert] = min(dp[i + 1][nj_insert], dp[i][j] + 1);
            }
            // 选项2:不插入,直接处理当前字符
            int nj_noinsert = trans[j][c - 'a'];
            if (nj_noinsert != m) {
                dp[i + 1][nj_noinsert] = min(dp[i + 1][nj_noinsert], dp[i][j]);
            }
        }
    }

    int ans = INF;
    for (int j = 0; j < m; ++j) {
        ans = min(ans, dp[n][j]);
    }

    if (ans == INF) {
        cout << -1 << endl;
    } else {
        cout << ans << endl;
    }

    return 0;
}
0