Solve the problem merging the stacks consisting rocks

 The outputs:

3                 
1 2 3
9
7                 
13 7 8 16 21 4 18 
239
7                 
13 7 8 16 21 4 18
239
exit

The corresponding codes:

// mergering the rock stacks into a single one with the lowest cost 
# include <iostream>
# include <iomanip>
# include <vector>
# include <climits>
using namespace std;
void generate_array(int* &a, int n);
void initialization(int rows, int columns, vector<vector<int>>& dp);
void merging_stacks(int* &a, int n, vector<vector<int>>& dp);
int main()
{
    int n = 0; //the number of stacks to merge
    while(cin >> n){
    // initialize the required variables for mergering function
    int *a; //the pointer points the array containing the number of each stack
    generate_array(a, n); //generate an array with length of n elements
    int temp;
    for(int i = 0; i < n; i++){
        cin >> temp;
        a[i] = temp;   //get the number of elements in the stack and push it into the array in corresponding position
    }
    vector<vector<int>> dp;
    initialization(n, n, dp); //initialize the dynamic programming matrix named dp
    merging_stacks(a, n, dp); //the lowest cost in merging the stacks
    delete a; //free the memory allocated for the array
    dp.clear();
    dp.shrink_to_fit();
    }
    return 0;
}
void generate_array(int* &a, int n)
{
    a = new int[n];
}
void initialization(int rows, int columns, vector<vector<int>>& dp)
{
    dp.resize(rows, vector<int>(columns, 1));
    for(int i = 0; i < rows; i++){
        dp[i][i] = 0;
    }
}
void merging_stacks(int* &a, int n, vector<vector<int>>& dp)
{
    int sum[n];
    sum[0] = a[0];
    for(int i = 1; i < n; i++){
        sum[i] = sum[i-1] + a[i];
    }
    for(int length = 1; length < n; length++){
        for(int i = 0; i < n - length; i++){   //notice the range of i
            int j = i + length;
            dp[i][j] = INT_MAX;
            int temp = sum[j] - ((i > 0) ? sum[i-1] : 0);
            for(int k = i; k < j; k++){
                dp[i][j] = min(dp[i][j],  dp[i][k] + dp[k+1][j] + temp); //key recursive equation in transformation from one state to another state
            }
        }
    }
    cout << dp[0][n-1] << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/121056351