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 pb push_back
# define ff first
# define ss second
# define nl "\n"
# define sz(x) ((int)(x).size())
# define deb(x) cerr << #x << " = " << x << endl;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const ll maxn = 1e5 + 25;
const ll inf = 1e18 + 0;
const ll mod = 1e9 + 7;
const ll dx[] = {0, -1, 1, 0};
const ll dy[] = {1, 0, 0, -1};
const ld eps = 1e-6;
using namespace std;
ll n, m;
string s, t;
ll dp[303][303];
void ma1n ()
{
cin >> n >> m;
cin >> s >> t;
s = "$" + s;
t = "$" + t;
for (ll i = 0; i <= n; ++i)
{
for (ll j = 0; j <= m; ++j)
{
dp[i][j] = inf;
}
}
dp[0][0] = 0;
for (ll i = 1; i <= n; ++i)
{
if (s[i] == t[1])
{
dp[i][1] = 1;
}
}
for (ll j = 2; j <= m; ++j)
{
for (ll i = 1; i <= n; ++i)
{
if (s[i] == t[j])
{
for (ll k = 1; k <= n; ++k)
{
if (s[k] == t[j - 1] && k != i)
{
dp[i][j] = min(dp[i][j], dp[k][j - 1] + abs(i - k));
}
}
}
for (ll k = 1; k <= n; ++k)
{
if (s[k] == s[i])
{
dp[k][j] = min(dp[k][j], dp[i][j] + abs(i - k));
}
}
}
}
ll ans = inf;
for (ll i = 1; i <= n; ++i)
{
ans = min(ans, dp[i][m]);
}
if (ans == inf) ans = 0;
cout << ans - 1 << nl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
// freopen("file.in", "r", stdin);
// freopen("file.out", "w", stdout);
int ttt = 1;
// cin >> ttt;
for (int test = 1; test <= ttt; ++test)
{
// cout << "Case " << test << ":" << ' ';
ma1n();
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |