Skip to content

Commit 6c37584

Browse files
committed
2312 new algo added.
1 parent 01b66db commit 6c37584

File tree

3 files changed

+64
-2
lines changed

3 files changed

+64
-2
lines changed

2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ project(D)
33

44
set(CMAKE_CXX_STANDARD 14)
55

6-
add_executable(D main.cpp)
6+
add_executable(D main2.cpp)

2001-2500/2312-Selling-Pieces-of-Wood/cpp-2312/main.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
using namespace std;
1010

1111

12-
/// DP
12+
/// DP - Knapback
1313
/// Time Complexity: O(m * n * n + n * m * m + m * n * (m + n))
1414
/// Space Complexity: O(m * n)
1515
class Solution {
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/// Source : https://leetcode.com/problems/selling-pieces-of-wood/
2+
/// Author : liuyubobobo
3+
/// Time : 2022-06-21
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <map>
8+
9+
using namespace std;
10+
11+
12+
/// DP
13+
/// Time Complexity: O(m * n * (m + n))
14+
/// Space Complexity: O(m * n)
15+
class Solution {
16+
public:
17+
long long sellingWood(int m, int n, vector<vector<int>>& prices) {
18+
19+
vector<vector<long long>> dp(m + 1, vector<long long>(n + 1, 0));
20+
vector<vector<bool>> visited(m + 1, vector<bool>(n + 1, false));
21+
22+
for(const vector<int>& price: prices){
23+
int h = price[0], w = price[1], p = price[2];
24+
dp[h][w] = max(dp[h][w], 1ll * p);
25+
}
26+
27+
return dfs(m, n, dp, visited);
28+
}
29+
30+
private:
31+
long long dfs(int m, int n, vector<vector<long long>>& dp, vector<vector<bool>>& visited){
32+
33+
if(visited[m][n]) return dp[m][n];
34+
35+
long long res = dp[m][n];
36+
for(int top = 1; top <= m - 1; top ++)
37+
res = max(res, dfs(top, n, dp, visited) + dfs(m - top, n, dp, visited));
38+
for(int left = 1; left <= n - 1; left ++)
39+
res = max(res, dfs(m, left, dp, visited) + dfs(m, n - left, dp, visited));
40+
41+
visited[m][n] = true;
42+
return dp[m][n] = res;
43+
}
44+
};
45+
46+
47+
int main() {
48+
49+
vector<vector<int>> prices1 = {{1, 4, 2}, {2, 2, 7}, {2, 1, 3}};
50+
cout << Solution().sellingWood(3, 5, prices1) << '\n';
51+
// 19
52+
53+
vector<vector<int>> prices2 = {{3, 2, 10}, {1, 4, 2}, {4, 1, 3}};
54+
cout << Solution().sellingWood(4, 6, prices2) << '\n';
55+
// 32
56+
57+
vector<vector<int>> prices3 = {{4, 1, 18}, {4, 2, 5}, {1, 1, 20}, {3, 1, 21}};
58+
cout << Solution().sellingWood(4, 2, prices3) << '\n';
59+
// 160
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)