From 9de08d31496b81289ac788ce7150a7e0015502e8 Mon Sep 17 00:00:00 2001 From: aucker Date: Sun, 12 May 2024 14:48:09 +0800 Subject: [PATCH] update: May 12, recursion --- daily/May12.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 daily/May12.cpp diff --git a/daily/May12.cpp b/daily/May12.cpp new file mode 100644 index 0000000..e562a43 --- /dev/null +++ b/daily/May12.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +class Solution { + public: + unordered_map memo; + int minDays(int n) { + if (n <= 1) { + return n; + } + + if (memo.count(n)) { + return memo[n]; + } + + return memo[n] = min(minDays(n / 2) + n % 2, minDays(n / 3) + n % 3) + 1; + } + + int minDaysDijkstra(int n) { + unordered_map dis; + priority_queue, vector>, greater<>> pq; + pq.emplace(0, n); + while (true) { + auto [dx, x] = pq.top(); + pq.pop(); + if (x <= 1) { + return dx + x; + } + if (dx > dis[x]) { + continue; + } + for (int d = 2; d <= 3; d++) { + int y = x / d; + int dy = dx + x % d + 1; + if (!dis.count(y) || dy < dis[y]) { + dis[y] = dy; + pq.emplace(dy, y); + } + } + } + } +}; \ No newline at end of file