#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>freq(26);
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;cin>>n>>m;
string s;
cin>>s;
string t;cin>>t;
for (int i = 0 ;i<n;++i){
freq[s[i]-'a'].push_back(i+1);
}
vector<vector<int64_t>>dp(m+2,vector<int64_t>(n+2,INT_MAX));
for (int i = 0;i<=n;++i){
dp[0][i]=0;
}
for (int i = 1;i<=m;++i){
for (int j = 1;j<=n;++j){
if (s[j-1]==t[i-1]){
dp[i][j]=min(dp[i][j],min(dp[i-1][j-1],dp[i-1][j+1])+1);
if (i==1)dp[i][j]=0;
for (auto x:freq[s[j-1]-'a']){
dp[i][x]=min(dp[i][j]+abs(j-x),dp[i][x]);
dp[i][x]=min(dp[i][j]+abs(j-x),dp[i][x]);
}
}
}
}
for (int i = 0;i<=n;++i){
dp[m][0]=min(dp[m][i],dp[m][0]);
}
if (dp[m][0]==INT_MAX)cout<<-1;
else
cout<<dp[m][0];
return 0;}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
3 |
Correct |
0 ms |
204 KB |
Output is correct |
4 |
Correct |
0 ms |
332 KB |
Output is correct |
5 |
Correct |
1 ms |
332 KB |
Output is correct |
6 |
Correct |
1 ms |
332 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
972 KB |
Output is correct |
2 |
Correct |
5 ms |
972 KB |
Output is correct |
3 |
Correct |
2 ms |
972 KB |
Output is correct |
4 |
Correct |
2 ms |
972 KB |
Output is correct |
5 |
Correct |
1 ms |
332 KB |
Output is correct |
6 |
Correct |
1 ms |
332 KB |
Output is correct |
7 |
Correct |
9 ms |
1048 KB |
Output is correct |
8 |
Correct |
32 ms |
972 KB |
Output is correct |
9 |
Correct |
65 ms |
972 KB |
Output is correct |
10 |
Correct |
1 ms |
332 KB |
Output is correct |
11 |
Correct |
6 ms |
1044 KB |
Output is correct |