Sure! Here's the C++ version of your effecientTrek Python function. This C++ program uses dynamic programming to solve the problem and produces the same output as your Python code.
#include <bits/stdc++.h>
using namespace std;
// Function to compute the minimum sum of maximums of d partitions
long long effecientTrek(const vector<int>& trails, int record) {
int n = trails.size();
int d = record;
const long long INF = 1e18;
// Initialize a DP table with INF
vector<vector<long long>> dp(n + 1, vector<long long>(d + 1, INF));
dp[0][0] = 0; // Base case: 0 trails and 0 partitions
// Iterate over each trail
for(int i = 1; i <= n; ++i){
// Iterate over the number of partitions
for(int k = 1; k <= min(d, i); ++k){
int maxi = 0;
// Iterate over possible partition sizes
for(int j = 1; j <= i - k + 1; ++j){
if(k - 1 > i - j){
continue; // Skip invalid partitions
}
maxi = max(maxi, trails[i - j]);
// Update DP table if a better solution is found
dp[i][k] = min(dp[i][k], dp[i - j][k - 1] + (long long)maxi);
}
}
}
return dp[n][d];
}
int main(){
vector<int> t = {10, 5, 9, 3, 8, 15};
int r = 2;
cout << effecientTrek(t, r) << endl; // Expected output: 25
return 0;
}
Explanation:
-
Initialization:
- We create a 2D DP table
dp of size (n+1) x (d+1) where n is the number of trails and d is the number of partitions (records).
- Initialize all values in
dp to INF (a very large number) to represent that initially, all states are unreachable.
- Set
dp[0][0] = 0 as the base case, meaning 0 trails and 0 partitions cost nothing.
-
Dynamic Programming:
- Iterate through each trail
i from 1 to n.
- For each trail, iterate through each possible number of partitions
k from 1 to min(d, i) to ensure we don't exceed the number of partitions or trails.
- For each partition size
j, update the maxi to keep track of the maximum trail height in the current partition.
- Update the
dp[i][k] by taking the minimum of its current value and the cost of the previous state dp[i-j][k-1] plus the current maxi.
-
Final Answer:
- The answer is stored in
dp[n][d], which represents the minimum sum of maximums for partitioning all n trails into d partitions.
Output:
When you run this program with the provided trails vector and record = 2, it will output:
25
This matches the output of your original Python code.