#include <bits/stdc++.h>
using namespace std;
const int nx=305;
int n, m, dp[nx][nx], res=1e9;
string a, b;
int main()
{
    cin.tie(NULL)->sync_with_stdio(false);
    cin>>n>>m>>a>>b;
    for (int i=0; i<n; i++) dp[0][i]=(a[i]==b[0])?0:1e9;
    for (int i=1; i<m; i++)
    {
        for (int j=0; j<n; j++) for (int k=0; k<n; k++) if (a[j]==a[k]) dp[i-1][k]=min(dp[i-1][k], dp[i-1][j]+abs(j-k));
        for (int j=0; j<n; j++)
        {
            dp[i][j]=1e9;
            if (a[j]==b[i])
            {
                if (j>0) dp[i][j]=min(dp[i][j], dp[i-1][j-1]+1);
                if (j<n-1) dp[i][j]=min(dp[i][j], dp[i-1][j+1]+1); 
            }
        }
    }
    for (int i=0; i<n; i++) res=min(res, dp[m-1][i]);
    if (res>=1e9) cout<<-1;
    else cout<<res;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |