#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int inf=1e12;
signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int n,m; cin>>n>>m;
    string a,b; cin>>a>>b;
    a=" "+a, b=" "+b;
    vector<vector<int>> dist(n+1,vector<int>(m+1,-1));
    priority_queue<vector<int>> q;
    for (int i=1; i<=n; i++) if (a[i]==b[1]) q.push({0,i,1});
    int ans=-1;
    while(!q.empty()){
        vector<int> v=q.top(); q.pop();
        int i=v[1], j=v[2], d=-v[0];
        if (dist[i][j]!=-1) continue;
        dist[i][j] = d;
        if (j==m) {
            ans=d;
            break;
        }
        //now simulate a scroll
        if (i-1>=1 and a[i-1]==b[j+1]) {
            q.push({-(d+1),i-1,j+1});
        }
        if (i+1<=n and a[i+1]==b[j+1]) {
            q.push({-(d+1),i+1,j+1});
        }
        //now simulate a jump
        for (int k=1; k<=n; k++) if (a[i]==a[k]){
            q.push({-(d+abs(i-k)),k,j});
        }
    } 
    for (int i=1; i<=n; i++){
        for (int j=1; j<=m; j++){
            //cout<<i<<' '<<j<<' '<<dist[i][j]<<'\n';
        }
    }
    cout<<ans<<'\n';
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |