This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#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;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |