This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//------------------------------------\
//   ------------------------------   \
//  |    created by Pham Phuongg   |  \
//  |       phamvuphuong2008       |  \
//  |     THPT CHUYEN HA TINH      |  \
//  |      HA TINH, VIET NAM       |  \
//  |    Bé Phương from TK4-CHT    |  \
//   ------------------------------   \
//------------------------------------\
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define pb push_back
#define fi first
#define se second
#define ii pair<int,int>
#define iii pair<int,ii>
using namespace std;
const int maxn = 3e2+5;
int n,m, dp[maxn][30][maxn];
string s;
vector<int>pos[30];
main() {
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
   
    cin >> n >> m >> s;
    s = " " + s;
    for (int i = 1; i <= n; i++) pos[s[i] - 'a'].pb(i);
    cin >> s;
	s = " " + s;
	memset(dp, 0x3f, sizeof dp);
	for (int x : pos[s[1] - 'a']) {
		dp[1][s[1] - 'a'][x] = 0;
	}
	for (int i = 2; i <= m; i++) {
		for (int x : pos[s[i] - 'a']) {
			for (int y : pos[s[i-1] - 'a']) {
				if (x != y)
				dp[i][s[i]-'a'][x] = min(dp[i][s[i]-'a'][x], dp[i-1][s[i-1]-'a'][y] + abs(x - y));
			}
		}
	}
	int mini = 1e18;
	for (int x : pos[s[m] - 'a']) {
		mini = min(mini, dp[m][s[m]-'a'][x]);
	}
	if (mini == 1e18) cout << "-1";
	else cout << mini;
}
Compilation message (stderr)
bajka.cpp:1:1: warning: multi-line comment [-Wcomment]
    1 | //------------------------------------\
      | ^
bajka.cpp:24:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
   24 | main() {
      | ^~~~| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |