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;
long long n, m, minn = INT_MAX;
string s, t;
vector<int> ch[27];
long long backtrack(int id, int pos)
{
if(pos == m)
{
return 0;
}
long long ans = INT_MAX;
for(int i : ch[s[id] - 96])
{
if(i < n - 1 && s[i + 1] == t[pos])
{
ans = min(ans, backtrack(i + 1, pos + 1) + abs(id - i) + 1);
}
if(i > 0 && s[i - 1] == t[pos])
{
ans = min(ans, backtrack(i - 1, pos + 1) + abs(id - i) + 1);
}
}
return ans;
}
int main()
{
cin >> n >> m;
cin>> s;
cin>> t;
for(int i = 0; i < n; i++)
{
ch[s[i] - 96].push_back(i);
}
for(int c : ch[t[0] - 96])
{
minn = min(minn, backtrack(c, 1));
}
if(minn < INT_MAX)
{
cout << minn;
return 0;
}
cout << -1;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |