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;
#pragma GCC optimize ("Ofast")
#define F first
#define S second
#define vi vector<int>
#define vvi vector<vi>
#define pi pair<int, int>
#define vpi vector<pi>
#define vb vector<bool>
#define vvb vector<vb>
#define pb push_back
#define ppb pop_back
#define read(a) for(auto &x:a) cin >> x;
#define print(a) for(auto x:a) cout << x << " "; cout << "\n";
#define vc vector<char>
#define vvc vector<vc>
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define int long long
#define ld long double
const int INF = 1e18;
const int inf = 1e9;
void solve(){
int n, m; cin >> n >> m;
string s, t; cin >> s >> t;
vvi dp(n, vi(m, INF));
for(int i=0; i<n; i++)
if(s[i] == t[0]) dp[i][0] = 0;
for(int j=0; j<m; j++){
for(int i=0; i<n && j > 0; i++)
if(s[i] == t[j]){
if(i-1 >= 0) dp[i][j] = min(dp[i][j], dp[i-1][j-1]+1);
if(i+1 < n) dp[i][j] = min(dp[i][j], dp[i+1][j-1]+1);
}
for(int i=0; i<n; i++)
for(int k=0; k<n; k++)
if(s[i] == s[k] && i != k) dp[i][j] = min(dp[i][j], dp[k][j]+abs(k-i));
}
int ans = INF;
for(int i=0; i<n; i++)
ans = min(ans, dp[i][m-1]);
cout << (ans == INF ? -1 : ans) << "\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int tt = 1;
// cin >> tt;
while(tt--)
solve();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |