#include <bits/stdc++.h>
using namespace std;
const int N = 305;
int n, m, dp[N][N];
string s, t;
vector<int> inds[26];
int main(){
cin >> n >> m >> s >> t;
for (int i = 0; i < n; i ++)
inds[s[i] - 'a'].push_back(i);
for (int j = 1; j < m; j ++){
char want = t[m - j];
for (int i = 0; i < n; i ++){
dp[i][j] = 1e9;
for (int k : inds[s[i] - 'a']){
if (k - 1 >= 0 and s[k - 1] == want)
dp[i][j] = min(dp[i][j], abs(i - k) + 1 + dp[k - 1][j - 1]);
if (k + 1 < n and s[k + 1] == want)
dp[i][j] = min(dp[i][j], abs(i - k) + 1 + dp[k + 1][j - 1]);
}
}
}
int ans = 1e9;
for (int i : inds[t[0] - 'a'])
ans = min(ans, dp[i][m - 1]);
if (ans == 1e9)
ans = -1;
cout << ans << endl;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
348 KB |
Output is correct |
2 |
Correct |
1 ms |
348 KB |
Output is correct |
3 |
Correct |
0 ms |
348 KB |
Output is correct |
4 |
Correct |
0 ms |
348 KB |
Output is correct |
5 |
Correct |
0 ms |
348 KB |
Output is correct |
6 |
Correct |
0 ms |
348 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
804 KB |
Output is correct |
2 |
Correct |
13 ms |
604 KB |
Output is correct |
3 |
Correct |
7 ms |
600 KB |
Output is correct |
4 |
Correct |
6 ms |
604 KB |
Output is correct |
5 |
Correct |
1 ms |
600 KB |
Output is correct |
6 |
Correct |
1 ms |
604 KB |
Output is correct |
7 |
Correct |
13 ms |
600 KB |
Output is correct |
8 |
Correct |
31 ms |
604 KB |
Output is correct |
9 |
Correct |
62 ms |
600 KB |
Output is correct |
10 |
Correct |
1 ms |
604 KB |
Output is correct |
11 |
Correct |
10 ms |
804 KB |
Output is correct |