Skip to content

Commit

Permalink
update: May 12, recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
aucker committed May 12, 2024
1 parent 4eb326f commit 9de08d3
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions daily/May12.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
unordered_map<int, int> 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<int, int> dis;
priority_queue<pair<int, int>, vector<pair<int, int>>, 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);
}
}
}
}
};

0 comments on commit 9de08d3

Please sign in to comment.