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>
#define in(x) freopen(x, "r", stdin)
#define out(x) freopen(x, "w", stdout)
using namespace std;
const int man = (int)(3e2 + 10);
const int mam = (int)(3e2 + 10);
int n, m;
string s, t;
int dp[man][mam];
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifdef _LOCAL
in("inB.txt");
out("outB.txt");
#endif
cin >> n >> m;
cin >> s;
cin >> t;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
dp[i][j] = 1e9;
}
}
for (int i = 1; i <= n; ++i) {
if (s[i - 1] == t[0]) {
dp[1][i] = 0;
}
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[j - 1] != t[i - 1]) {
continue;
}
for (int k = 1; k <= n; ++k) {
if (s[k - 1] != t[i - 1]) {
continue;
}
if ((k - 1) >= 1) {
if (s[k - 2] == t[i]) {
dp[i + 1][k - 1] = min(dp[i + 1][k - 1], dp[i][j] + abs(j - k) + 1);
}
}
if ((k + 1) <= n) {
if (s[k] == t[i]) {
dp[i + 1][k + 1] = min(dp[i + 1][k + 1], dp[i][j] + abs(j - k) + 1);
}
}
}
}
}
int ans = 1e9;
for (int i = 1; i <= n; ++i) {
if (s[i - 1] != t.back()) {
continue;
}
ans = min(ans, dp[m][i]);
}
if (ans == 1e9) {
cout << "-1\n";
} else {
cout << ans << "\n";
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |