[AlgoExpert] Disk Stacking

Disk Stacking

  • Time : O(n^2)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <vector>
using namespace std;

int helper(vector<vector<int>>& d, vector<int>& dp, vector<int>& path, int p) {
if(dp[p] != -1) return dp[p];
int n = d.size();
int& res = dp[p] = d[p][2];
for(int i = 0; i < n; i++) {
if(d[i][0] >= d[p][0] or d[i][1] >= d[p][1] or d[i][2] >= d[p][2]) continue;
int h = d[p][2] + helper(d, dp, path, i);
if(h > res) {
res = h;
path[p] = i;
}
}
return res;
}

vector<vector<int>> diskStacking(vector<vector<int>> disks) {
int n = disks.size(), ma = 0, root = -1;
vector<int> dp(n, -1), path(n, -1);
for(int i = 0; i < n; i++) {
if(helper(disks, dp, path, i) > ma) {
ma = dp[i];
root = i;
}
}
vector<vector<int>> res;
while(root != -1) {
res.push_back(disks[root]);
root = path[root];
}
reverse(begin(res), end(res));
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/disk-stacking/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.