// rewritten
#include <bits/stdc++.h>
#define int long long
#define double long double
#define pii pair <int,int>
#define tiii tuple <int, int, int>
#define f first
#define s second
#define all(x) x.begin(), x.end()
#define ub(a, b) upper_bound(a.begin(), a.end(), b) - a.begin()
#define lb(a, b) lower_bound(a.begin(), a.end(), b) - a.begin()
#define ve vector
#define graph(a, n) vector <int> a[n];
#define wgraph(a, n) vector <pii> a[n];
#define emb emplace_back
#define em emplace
#define ins insert
#define er erase
#define iShowSpeed cin.tie(NULL)->sync_with_stdio(false)
using namespace std;
template <typename T>
using greater_priority_queue = priority_queue<T, vector<T>, greater<T>>;
const int mod = 1e9 + 7;
const int inf = 1e18;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int32_t main(){
    iShowSpeed;
    int n, m; cin >> n >> m;
    string a, b; cin >> a >> b;
    a = ' ' + a;
    b = ' ' + b;
    vector <vector <int>> dp(m + 2, vector <int> (n + 2, inf)); // dp[i][j] = min time needed to end character i at position j
    for (int i = 0; i <= n; i++) if (a[i] == b[1]) dp[1][i] = 0;
    for (int i = 2; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (a[j] != b[i]) continue;
            dp[i][j] = min({dp[i][j], dp[i - 1][j - 1] + 1, dp[i - 1][j + 1] + 1});
        }
        for (int j = 1; j <= n; j++) {
            if (a[j] != b[i]) continue;
            for (int k = 1; k <= n; k++) {
                if (j == k || a[j] != a[k]) continue;
                dp[i][j] = min(dp[i][j], dp[i][k] + abs(j - k));
            }
        }
    }
    // for (int i = 1; i <= m; i++) {
    //     for (int j = 1; j <= n; j++) {
    //         if (dp[i][j] == inf) cout << "X ";
    //         else cout << dp[i][j] << " ";
    //     }
    //     cout << "\n";
    // }
    int ans = *min_element(all(dp[m]));
    cout << (ans == inf ? -1 : ans);
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |