Submission #511523

#TimeUsernameProblemLanguageResultExecution timeMemory
511523KoDBajka (COCI20_bajka)C++17
70 / 70
258 ms3776 KiB
#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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...