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 lcm(a,b) (a/__gcd(a,b))*b
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define pb push_back
#define F first
#define S second
#define mp make_pair
//salida rapida "\n"
//DECIMALES fixed<<sp(n)<<x<<endl;
//gcd(a,b)= ax + by
//lCB x&-x
//set.erase(it) - ersases the element present at the required index//auto it = s.find(element)
//set.find(element) - iterator pointing to the given element if it is present else return pointer pointing to set.end()
//set.lower_bound(element) - iterator pointing to element greater than or equal to the given element
//set.upper_bound(element) - iterator pointing to element greater than the given element
// | ^
//stoll string to long long
using namespace std;
int n,m;
int dp[305][305];
bool ok=false;
map<char, vi >M;
string ss,s;
//minimo si esto en posicion i y quiero escribir ss[ll]
void init(){
for(int i=0;i<305;i++){
for(int l=0;l<305;l++){
dp[i][l]=-1;
}
}
}
int f(int pos, int poss){
if(poss==m){
return -1;
}
if(ss[poss]!=s[pos]){
return 1e9;
}
if(dp[pos][poss]!=-1){
return dp[pos][poss];
}
dp[pos][poss]=1e9;
if(pos+1<n){
dp[pos][poss]=min(dp[pos][poss],f(pos+1,poss+1)+1);
}
if(pos-1>=0){
dp[pos][poss]=min(dp[pos][poss],f(pos-1,poss+1)+1);
}
for(auto it : M[s[pos]]){
if(it==pos)continue;
if(it+1<n && (it+1!=pos)){
dp[pos][poss]=min(dp[pos][poss],f(it+1,poss+1)+abs(pos-it)+1);
}
if(it-1>=0 && (it-1!=pos)){
dp[pos][poss]=min(dp[pos][poss],f(it-1,poss+1)+abs(it-pos)+1);
}
}
return dp[pos][poss];
}
int main()
{
init();
cin>>n>>m;
cin>>s>>ss;
for(int i=0;i<n;i++){
M[s[i]].pb(i);
}
if(s.size()==1){
if(s==ss){
cout<<0<<endl;
}else{
cout<<-1<<endl;
}
return 0;
}
int res=1e9;
for(auto it : M[ss[0]]){
//int aux=f(it,0);
res=min(res,f(it,0));
}
if(res==1e9){
cout<<-1<<endl;
}else{
cout<<res<<endl;
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |