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 sp << " " <<
#define int long long
#define vi vector<int>
#define pb push_back
#define F(xxx,yyy) for (int xxx=1;xxx<=yyy;xxx++)
const int N = 2e5+1;
void solve() {
int n,m;
cin >> n >> m;
string s="0",t="0",ss,tt;
cin >> ss >> tt;
s+=ss;
t+=tt;
s+="D";
t+="D";
int dp[m+1][n+1];
for (int i=0;i<=m;i++){
for (int j=1;j<=n;j++){
dp[i][j] = 1e18;
}
}
for (int i=1;i<=n;i++) dp[s[i]==t[1]][i] = 0;
vector<vi> posses(26);
for (int i=1;i<=n;i++) posses[s[i]-'a'].pb(i);
for (int i=0;i<m;i++) {
for (int j=1;j<=n;j++) {
if (s[j+1] == t[i+1]) dp[i+1][j+1] = min(dp[i+1][j+1],dp[i][j]+1);
if (s[j-1] == t[i+1]) dp[i+1][j-1] = min(dp[i+1][j-1],dp[i][j]+1);
}
for (int c=0;c<26;c++){
for (auto it : posses[c]) {
for (auto it2 : posses[c]) {
dp[i+1][it] = min(dp[i+1][it],dp[i+1][it2]+abs(it-it2));
}
}
}
}
int ans = *min_element(dp[m]+1,dp[m]+n+1);
cout << (ans==1e18?-1:ans) << endl;
}
signed main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
//cin >> t;
while (t --> 0) solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |