This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
#define int long long
#define mp make_pair
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define nbits(x) __builtin_popcount(x)
#define gcd(x, y) __gcd(x, y)
#define SYNC_OFF ios::sync_with_stdio(0); cin.tie(0);
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vii;  
const int MOD = 1e9 + 7; // 998244353;
const int N = 301;
const int INF = 1e15; // 1e18;
const double PI = acos(-1);
const int dx[] = {-1,0,1,0,-1,1,1,-1};
const int dy[] = {0,1,0,-1,1,1,-1,-1};
int powmod(int a, int b, int m = MOD) {
    int res = 1;
    a %= m; assert(b >= 0);
    for (; b; b>>=1) {
        if (b & 1) res = res*a % m;
        a = a*a % m;
    }
    return res;
}
int n, m;
string s, f;
int dp[N][N];
// dp[i][j] =  at i-th pos in s & need to make f[j]
int solve(int i, int j) {
    if (j == m) return 0;
    if (dp[i][j] != -1) return dp[i][j];
    int ans = INF;
    for (int k = 0; k < n; k++) {
        if (s[i] == s[k]) {
            if (k+1 < n && s[k+1] == f[j]) {
                ans = min(ans, solve(k+1, j+1) + abs(i-k) + 1);
            }
            if (0 <= k-1 && s[k-1] == f[j]) {
                ans = min(ans, solve(k-1, j+1) + abs(i-k) + 1);
            }
        }
    }
    return dp[i][j] = ans;
}
signed main() {
    SYNC_OFF;
    cin >> n >> m >> s >> f;
    memset(dp, -1, sizeof dp);
    int ans = INF;
    for (int i = 0; i < n; i++) {
        if (s[i] == f[0]) {
            ans = min(ans, solve(i, 1));
        }
    }
    cout << (ans == INF ? -1 : ans) << "\n"; 
    return 0;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |