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>
#define loop(i, a, b) for(long long i=a;i<b;i++)
#define pool(i, a, b) for(long long i=a-1;i>=b;i--)
#define fore(i, a) for(auto&& i:a)
#define fi first
#define se second
#define ps(a) push_back(a)
#define pb(a) pop_back(a)
#define sc scanf
#define vc vector
#define pa pair<ll, ll>
#define ll long long
#define lb lower_bound
#define ub upper_bound
#define all(a) a.begin(), a.end()
#define llmax LLONG_MAX/2
#define llmin -LLONG_MAX/2
using namespace std;
#define mn 310
#define pa pair<ll, ll>
#define ld long double
ll dp[mn][mn];
int main() {
ll n, m;cin >> n >> m;
string a, b;cin >> a >> b;
loop(i, 1, m+1){
loop(j, 1, n+1) dp[i][j]=llmax;
loop(j, 1, n+1)if(a.at(j-1)==b.at(i-1)){
if(i==1) dp[i][j]=min(dp[i][j], (ll)0);
if(j-1>=1)dp[i][j]=min(dp[i][j], dp[i-1][j-1]+1);
if(j+1<=n)dp[i][j]=min(dp[i][j], dp[i-1][j+1]+1);
}
loop(j, 1, n+1)if(a.at(j-1)==b.at(i-1)){
loop(k, 1, n+1) if(k!=j and a.at(k-1)==a.at(j-1)) dp[i][j]=min(dp[i][j], dp[i][k]+abs(k-j));
pool(k, n+1, 1) if(k!=j and a.at(k-1)==a.at(j-1)) dp[i][j]=min(dp[i][j], dp[i][k]+abs(k-j));
}
}
ll ans=llmax;
loop(j, 1, n+1) ans=min(ans, dp[m][j]);
cout << ((ans>=llmax/2) ? -1 : ans)<<endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |