#include <bits/stdc++.h>
#define ST first
#define ND second
#define PB push_back
using namespace std;
using ll = long long;
using pi = pair<int,int>;
using vi = vector<int>;
const int nax = 310, INF = 1e9;
int n, m;
string a, b;
int dp[nax][nax];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> a >> b;
for(int i = m - 1; i >= 1; --i) {
for(int j = 0; j < n; ++j) {
dp[i][j] = INF;
if(j > 0 && a[j - 1] == b[i]) {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1] + 1);
}
if(j < n - 1 && a[j + 1] == b[i]) {
dp[i][j] = min(dp[i][j], dp[i + 1][j + 1] + 1);
}
}
for(int j = 0; j < n; ++j) {
for(int k = 0; k < n; ++k) {
if(a[k] != a[j]) continue;
dp[i][j] = min(dp[i][j], dp[i][k] + abs(k - j));
}
}
}
int ans = INF;
for(int i = 0; i < n; ++i) {
if(a[i] == b[0]) {
ans = min(ans, dp[1][i]);
}
}
if(ans == INF) cout << "-1";
else cout << ans;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
588 KB |
Output is correct |
3 |
Correct |
1 ms |
332 KB |
Output is correct |
4 |
Correct |
1 ms |
588 KB |
Output is correct |
5 |
Correct |
1 ms |
588 KB |
Output is correct |
6 |
Correct |
2 ms |
588 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
71 ms |
616 KB |
Output is correct |
2 |
Correct |
61 ms |
612 KB |
Output is correct |
3 |
Correct |
58 ms |
632 KB |
Output is correct |
4 |
Correct |
59 ms |
712 KB |
Output is correct |
5 |
Correct |
4 ms |
332 KB |
Output is correct |
6 |
Correct |
4 ms |
332 KB |
Output is correct |
7 |
Correct |
76 ms |
660 KB |
Output is correct |
8 |
Correct |
62 ms |
580 KB |
Output is correct |
9 |
Correct |
100 ms |
632 KB |
Output is correct |
10 |
Correct |
2 ms |
332 KB |
Output is correct |
11 |
Correct |
79 ms |
656 KB |
Output is correct |