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;
#define int long long
#define all(x) (x).begin(), (x).end()
#define pii pair<int, int>
#define fi first
#define se second
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
string a, b;
cin >> a >> b;
vector<int> dp(n, (int) 1e18);
for (int i = 0; i < n; i++) {
if (a[i] == b[0]) {
dp[i] = 0;
}
}
for (int j = 1; j < m; j++) {
vector<int> dp2(n, (int) 1e18);
for (int i = 0; i < n; i++) {
for (int pos = 0; pos < n; pos++) {
if (a[pos] == b[j]) {
if (abs(i - pos) == 1) {
dp2[pos] = min(dp2[pos], dp[i] + 1);
}
if (pos && a[pos - 1] == a[i]) {
dp2[pos] = min(dp2[pos], dp[i] + abs(i - (pos - 1)) + 1);
}
if (pos + 1 < n && a[pos + 1] == a[i]) {
dp2[pos] = min(dp2[pos], dp[i] + abs(i - (pos + 1)) + 1);
}
}
}
}
swap(dp, dp2);
}
if (*min_element(all(dp)) == (int) 1e18) {
cout << -1;
return 0;
}
cout << *min_element(all(dp));
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |