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;
int n, m;
string workOn, goal;
int main(){
cin >> n >> m;
cin >> workOn >> goal;
if(m > n){
cout << -1 << endl;
return 0;
}
if(m == 1){
bool exists = false;
for(int i = 0; i < n; ++i){
if(workOn[i] == goal[0]) exists = true;
}
if(exists) cout << 0 << endl;
else cout << -1 << endl;
return 0;
}
vector<vector<int>> dp(m-1, vector<int>(n, 1e9));
for(int i = 0; i < n; ++i){
if(workOn[i] == goal[0]){
if(i){
if(workOn[i-1] == goal[1]){
dp[0][i-1] = 1;
}
}
if(i <(n-1)){
if(workOn[i+1] == goal[1]){
dp[0][i+1] = 1;
}
}
}
}
for(int letterNum = 1; letterNum < m-1; ++letterNum){
for(int actualPosition = 0; actualPosition < n; ++actualPosition){
if(workOn[actualPosition] != goal[letterNum]) continue;
int bestPrev = 1e9;
for(int prevPosition = 0; prevPosition < n; ++prevPosition){
if(dp[letterNum-1][prevPosition] == 1e9) continue;
bestPrev = min(bestPrev, abs(prevPosition - actualPosition)+dp[letterNum-1][prevPosition]);
}
if(actualPosition){
if(workOn[actualPosition-1] == goal[letterNum+1]){
dp[letterNum][actualPosition-1] = 1 + bestPrev;
}
}
if(actualPosition < (n-1)){
if(workOn[actualPosition+1] == goal[letterNum+1]){
dp[letterNum][actualPosition+1] = 1 + bestPrev;
}
}
}
}
int ans = 1e9;
for(int i = 0; i < n; ++i) ans = min(ans, dp[m-2][i]);
if(ans == 1e9) cout << -1 << endl;
else cout << ans << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |