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 ll long long
#define ar array
const int INF = 1e9;
int n, m;
string s, t;
vector<int> pos[26];
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> m >> s >> t;
	for (int i = 0; i < n; ++i) pos[s[i] - 'a'].push_back(i);
	if (pos[t[0] - 'a'].empty()) {
		cout << -1;
		return 0;
	}
	vector<int> dp(pos[t[0] - 'a'].size());
	for (int i = 1; i < m; ++i) {
		int c = t[i] - 'a';
		int c2 = t[i - 1] - 'a';
		vector<int> ndp(pos[c].size(), INF);
		for (int j = 0; j < pos[c2].size(); ++j) {
			for (int k = 0; k < pos[c].size(); ++k) {
				if (abs(pos[c2][j] - pos[c][k]) == 1) {
					ndp[k] = min(ndp[k], dp[j] + 1);
				}
			}
		}
		swap(dp, ndp);
		for (int i = 0; i < dp.size(); ++i) {
			for (int j = 0; j < dp.size(); ++j) {
				dp[j] = min(dp[j], dp[i] + abs(pos[c][i] - pos[c][j]));
			}
		}
		if (dp.empty() || *min_element(dp.begin(), dp.end()) == INF) {
			cout << -1;
			return 0;
		}
	}
	cout << *min_element(dp.begin(), dp.end());
	return 0;
}
Compilation message (stderr)
bajka.cpp: In function 'int main()':
bajka.cpp:26:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   26 |   for (int j = 0; j < pos[c2].size(); ++j) {
      |                   ~~^~~~~~~~~~~~~~~~
bajka.cpp:27:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   27 |    for (int k = 0; k < pos[c].size(); ++k) {
      |                    ~~^~~~~~~~~~~~~~~
bajka.cpp:34:21: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   34 |   for (int i = 0; i < dp.size(); ++i) {
      |                   ~~^~~~~~~~~~~
bajka.cpp:35:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   35 |    for (int j = 0; j < dp.size(); ++j) {
      |                    ~~^~~~~~~~~~~| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |