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 <iostream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <set>
#include <map>
#include <cassert>
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ll long long
#define ii pair<int,int>
#define pll pair<long long, long long>
#define fi first
#define se second
#define r first
#define c second
#define all(x) x.begin(), x.end()
ostream& operator << (ostream& os, pair<int, int> a) {
return os << a.first << " : " << a.second;
}
#define endl '\n'
#define db(val) "["#val" = "<<(val)<<"] "
#define cntbit(x) __builtin_popcount(x)
const int N = 500 + 5;
const int iINF = 1e9;
const ll MOD = 1e9 + 7;
const ll MOD2 = 998244353;
const ll INF = 1e18;
int n, m;
string s, t;
ll dp[N][N];
int main() {
#ifdef CHUNGDINH
freopen("main.inp","r",stdin);
//freopen("main.out","w",stdout);
#endif
cin >> n >> m >> s >> t;
s = '#' + s, t = '#' + t;
if (m == 1) {
if (s == t) cout << 0; else cout << -1;
return 0;
}
for (int i = 1; i <= n; i++) {
dp[i][1] = INF;
if (s[i] == t[1]) dp[i][1] = 0;
}
ll res = INF;
for (int k = 2; k <= m; k++) {
for (int i = 1; i <= n; i++) {
dp[i][k] = INF;
if (s[i] != t[k]) continue;
for (int j = 1; j <= n; j++) {
if (s[j] != t[k - 1]) continue;
if (j >= 2 && s[j - 1] == s[i]) {
dp[i][k] = min(dp[i][k], dp[j][k - 1] + abs(i - (j - 1)) + 1);
}
if (j <= n - 1 && s[j + 1] == s[i]) {
dp[i][k] = min(dp[i][k], dp[j][k - 1] + abs(i - (j + 1)) + 1);
}
}
if (k == m) res = min(res, dp[i][k]);
}
}
if (res >= INF) res = -1;
cout << res;
}
/*
Array bounds *
long long vs int
Garbage value
Sometimes, VNOI views "arrays out of bounds" as "wrong answer"
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |