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 std::vector;
using std::array;
using std::pair;
using std::tuple;
template <class F> struct RecLambda : private F {
explicit RecLambda(F&& f) : F(std::forward<F>(f)) {}
template <class... Args> decltype(auto) operator()(Args&&... args) const {
return F::operator()(*this, std::forward<Args>(args)...);
}
};
template <class T> using Heap = std::priority_queue<T, vector<T>, std::greater<>>;
constexpr int inf = std::numeric_limits<int>::max() / 2;
bool setmin(int& x, const int y) {
if (x > y) {
x = y;
return true;
}
return false;
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int N, M;
std::cin >> N >> M;
vector<char> S(N), T(M);
for (auto& x : S) {
std::cin >> x;
}
for (auto& x : T) {
std::cin >> x;
}
vector dp(M, vector(N, inf));
Heap<tuple<int, int, int>> que;
const auto push = [&](const int m, const int i, const int d) {
if (setmin(dp[m][i], d)) {
que.emplace(d, m, i);
}
};
for (int i = 0; i < N; ++i) {
push(M - 1, i, 0);
}
while (!que.empty()) {
const auto [d, m, i] = que.top();
que.pop();
if (d > dp[m][i]) {
continue;
}
if (m > 0 and T[m] == S[i]) {
if (i > 0) {
push(m - 1, i - 1, d + 1);
}
if (i + 1 < N) {
push(m - 1, i + 1, d + 1);
}
}
for (int j = 0; j < N; ++j) {
if (S[i] == S[j]) {
push(m, j, d + std::abs(i - j));
}
}
}
int ans = inf;
for (int i = 0; i < N; ++i) {
if (T[0] == S[i]) {
setmin(ans, dp[0][i]);
}
}
std::cout << (ans == inf ? -1 : ans) << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |