This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//author:
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define ONLINE_JUDGE
const int INF = 1e9 + 7;
const int MAXN = 300 + 5;
int dp[MAXN][MAXN];
void solve() {
memset(dp, -1, sizeof(dp));
int n, m;
cin >> n >> m;
string a, b;
cin >> a >> b;
a = '$' + a;
a = a + '$';
b = '$' + b;
b = b + '$';
function <int(int, int)> f = [&](int x, int al) -> int {
if(dp[x][al] != -1)
return dp[x][al];
if(al == m +1)
return 0;
int res = INF;
for(int i = 1; i <= n; i++) {
if(a[i] == b[al]) {
if(abs(i - x) == 1) {
res = min(res, f(i, al +1) + abs(i - x));
}
if(a[i +1] == a[x] && abs((i +1) - x) != 0) {
res = min(res, f(i, al +1) + abs((i +1) - x) + abs((i +1) - i));
}
if(a[i -1] == a[x] && abs((i -1) - x) != 0) {
res = min(res, f(i, al +1) + abs((i -1) - x) + abs((i -1) - i));
}
}
}
return dp[x][al] = res;
};
int ans = INF;
for(int i = 1; i <= n; i++) {
if(a[i] == b[1]) {
ans = min(ans, f(i, 2));
}
}
cout << (ans == INF ? -1 : ans);
return;
}
signed main() {
#ifndef ONLINE_JUDGE
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t = 1; //cin >> t;
while(t--)
solve();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |