#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define sz(a) (int)a.size()
#define all(a) a.begin(),a.end()
#define rep(i,n) for(int i=0;i<n;i++)
#define crep(i,x,n) for(int i=x;i<n;i++)
#define drep(i,n) for(int i=n-1;i>=0;i--)
#define vec(...) vector<__VA_ARGS__>
#define _3HaBFkZ ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
typedef long double ld;
using pii=pair<int,int>;
using vi=vector<int>;
int main(){
_3HaBFkZ;
int n,m;
cin>>n>>m;
string s,t;
cin>>s>>t;
vi dp(n,1e9),nedp(n,1e9);
rep(i,n){
if(s[i]==t[0]) dp[i]=0;
}
crep(j,1,m){
rep(i,n) nedp[i]=1e9;
char need=t[j];
auto affine=[&](int i,int val){
if(i>=0 and i<n and s[i]==need){
nedp[i]=min(nedp[i],val);
}
};
rep(i,n){
if(dp[i]==1e9) continue;
affine(i-1,dp[i]+1);
affine(i+1,dp[i]+1);
rep(nei,n){
if(s[nei]!=s[i]) continue;
if(nei-1>=0 or nei+1<n){
affine(nei-1,dp[i]+abs(i-nei)+1);
affine(nei+1,dp[i]+abs(i-nei)+1);
}
}
}
swap(dp,nedp);
}
int ans=*min_element(all(dp));
if(ans>=1e9) cout<<"-1\n";
else cout<<ans<<"\n";
//
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Correct |
0 ms |
204 KB |
Output is correct |
3 |
Correct |
0 ms |
204 KB |
Output is correct |
4 |
Correct |
0 ms |
204 KB |
Output is correct |
5 |
Correct |
0 ms |
204 KB |
Output is correct |
6 |
Correct |
0 ms |
204 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
3 |
Correct |
1 ms |
204 KB |
Output is correct |
4 |
Correct |
1 ms |
204 KB |
Output is correct |
5 |
Correct |
0 ms |
204 KB |
Output is correct |
6 |
Correct |
0 ms |
204 KB |
Output is correct |
7 |
Correct |
6 ms |
204 KB |
Output is correct |
8 |
Correct |
24 ms |
204 KB |
Output is correct |
9 |
Correct |
30 ms |
204 KB |
Output is correct |
10 |
Correct |
0 ms |
204 KB |
Output is correct |
11 |
Correct |
3 ms |
204 KB |
Output is correct |