#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};
bool check(vector <int> &a, vector <int> &b) {
vector <int> cnt(26);
for (auto e : a) cnt[e]++;
for (auto e : b) {
if (!cnt[e]) return false;
cnt[e]--;
}
return true;
}
int32_t main(){
iShowSpeed;
int n, m; cin >> n >> m;
string aa, bb; cin >> aa >> bb;
vector <int> a, b;
for (auto c : aa) a.emplace_back((int)(c - 'a'));
for (auto c : bb) b.emplace_back((int)(c - 'a'));
if (!check(a, b)) {
cout << -1;
return 0;
}
vector <vector <int>> dp(m + 1, vector <int> (n + 1, inf)); // dp[i][j] = min time to reach position i and end at position j
for (int i = 0; i <= n; i++) dp[0][i] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (a[j - 1] != b[i - 1]) continue;
for (int k = 1; k <= n; k++) {
if (j == k) continue;
if (i == 1 || a[k - 1] == b[i - 2]) {
dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(j - k));
}
}
}
}
cout << *min_element(dp[m].begin() + 1, dp[m].begin() + 1 + n) - 1;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |