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 mx=300+10;
typedef long long ll;
int inf=1e9;
const int mod=1e9+7;
int n,m;
string a,b;
vector<int>pos[27];
int dp[mx][mx];
//int ok[i][j];
int solve(int i,int idx){
if(idx==m-1){return 0;}
int &ret=dp[i][idx];
if(ret!=-1){return ret;}
//if(ret==-2){return inf;}
ret=inf;
if(i<n-1&&a[i+1]==b[idx+1]){
ret=min(ret,solve(i+1,idx+1)+1);
}
if(i>0&&a[i-1]==b[idx+1]){
ret=min(ret,solve(i-1,idx+1)+1);
}
int me=a[i]-'a';
for(auto it:pos[me]){
if(it!=i){
ret=min(ret,solve(it,idx)+(abs(i-it)));
}
}
return ret;
}
int main(){
cin>>n>>m;
cin>>a>>b;
memset(dp,-1,sizeof(dp));
for(int i=0;i<n;i++){
pos[a[i]-'a'].push_back(i);
}
if(pos[b[0]-'a'].size()==0){
cout<<-1;return 0;
}
int ans=inf;
for(auto it:pos[b[0]-'a']){
ans=min(ans, solve(it,0));
}
if(ans==inf){ans=-1;}
cout<<ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |