#include <bits/stdc++.h>
using namespace std;
using ll = long long;
unordered_map<char, vector<int>> mp; // positions where a letter shows up
const int INF = 1e9 + 5;
int n, m;
string scary, fav;
vector<vector<int>> dp(305, vector<int>(305, -1));
int go(int at, int id) {
if (id == m-1) {
return 0;
}
if (dp[at][id] != -1) {
return dp[at][id];
}
int ret = INF;
for(int i = 0; i < n; i++) {
if (scary[at] == scary[i]) {
if (i > 0 && scary[i-1] == fav[id+1]) {
ret = min(ret, go(i-1, id + 1) + abs(at - i) + 1);
}
if (i < n-1 && scary[i+1] == fav[id+1]) {
ret = min(ret, go(i+1, id + 1) + abs(at - i) + 1);
}
}
}
return dp[at][id] = ret;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m >> scary >> fav;
int ans = INF;
for(int i = 0; i < n; i++) {
if (scary[i] == fav[0]) {
ans = min(ans, go(i, 1));
}
}
cout << (ans >= INF ? -1 : ans) << "\n";
return 0;
}
//~ check for overflows
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
748 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
748 KB |
Output is correct |
2 |
Incorrect |
2 ms |
748 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |