#include<bits/stdc++.h>
using namespace std;
const int inf = 1'000'000'000;
int main()
{
int n, m;
string s, t;
cin >> n >> m >> s >> t;
int dp[n][m];
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
dp[i][j] = inf;
for(int i = 0; i < n; i ++)
if(s[i] == t[0]) dp[i][0] = 0;
for(int j = 0; j + 1 < m; j ++)
for(int i = 0; i < n; i++)
{
for(int k = 0; k < n; k++)
if(s[i] == s[k])
{
if(k > 0 && s[k - 1] == t[j + 1])
dp[k - 1][j + 1] = min(dp[k - 1][j + 1], dp[i][j] + 1 + abs(k - i));
if(k + 1 < n && s[k + 1] == t[j + 1])
dp[k + 1][j + 1] = min(dp[k + 1][j + 1], dp[i][j] + 1 + abs(k - i));
}
}
int ans = inf;
for(int i = 0; i < n; i ++)
ans = min(ans, dp[i][m - 1]);
if(ans == inf)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Correct |
0 ms |
348 KB |
Output is correct |
3 |
Correct |
0 ms |
344 KB |
Output is correct |
4 |
Correct |
0 ms |
348 KB |
Output is correct |
5 |
Correct |
1 ms |
348 KB |
Output is correct |
6 |
Correct |
0 ms |
348 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
27 ms |
604 KB |
Output is correct |
2 |
Correct |
27 ms |
780 KB |
Output is correct |
3 |
Correct |
23 ms |
692 KB |
Output is correct |
4 |
Correct |
25 ms |
604 KB |
Output is correct |
5 |
Correct |
2 ms |
344 KB |
Output is correct |
6 |
Correct |
2 ms |
344 KB |
Output is correct |
7 |
Correct |
32 ms |
604 KB |
Output is correct |
8 |
Correct |
38 ms |
604 KB |
Output is correct |
9 |
Correct |
62 ms |
604 KB |
Output is correct |
10 |
Correct |
1 ms |
348 KB |
Output is correct |
11 |
Correct |
29 ms |
604 KB |
Output is correct |