#include <bits/stdc++.h>
using namespace std;
int n, m, dp[510][510] = {0};
string s, t;
int main () {
memset(dp, 63, sizeof(dp));
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> m >> s >> t;
t = "%" + t;
for (int i = 0; i < n; i++) if (s[i] == t[1]) dp[1][i] = 0;
for (int i = 2; i <= m; i++) {
for (int j = 0; j < n; j++) {
if (s[j] != t[i]) continue;
if (j > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + 1);
if (j + 1 < n) dp[i][j] = min(dp[i][j], dp[i - 1][j + 1] + 1);
}
int mn = INT_MAX / 2;
for (int j = 0; j < n; j++) {
if (s[j] == t[i]) {
dp[i][j] = min(dp[i][j], mn + j);
mn = min(mn, dp[i][j] - j);
}
}
mn = INT_MAX / 2;
for (int j = n - 1; j >= 0; j--) {
if (s[j] == t[i]) {
dp[i][j] = min(dp[i][j], mn - j);
mn = min(mn, dp[i][j] + j);
}
}
}
int ans = INT_MAX;
for (int i = 0; i < n; i++) ans = min(ans, dp[m][i]);
if (ans > 100000) ans = -1;
cout << ans << '\n';
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
1368 KB |
Output is correct |
2 |
Correct |
1 ms |
1372 KB |
Output is correct |
3 |
Correct |
1 ms |
1472 KB |
Output is correct |
4 |
Correct |
1 ms |
1372 KB |
Output is correct |
5 |
Correct |
1 ms |
1372 KB |
Output is correct |
6 |
Correct |
1 ms |
1476 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
1372 KB |
Output is correct |
2 |
Correct |
1 ms |
1372 KB |
Output is correct |
3 |
Correct |
1 ms |
1372 KB |
Output is correct |
4 |
Correct |
1 ms |
1372 KB |
Output is correct |
5 |
Correct |
1 ms |
1372 KB |
Output is correct |
6 |
Correct |
1 ms |
1372 KB |
Output is correct |
7 |
Correct |
1 ms |
1372 KB |
Output is correct |
8 |
Correct |
1 ms |
1372 KB |
Output is correct |
9 |
Correct |
1 ms |
1368 KB |
Output is correct |
10 |
Correct |
1 ms |
1368 KB |
Output is correct |
11 |
Correct |
2 ms |
1368 KB |
Output is correct |