#41330: c++解答


yp11351205@yphs.tp.edu.tw (809-36黃泊霖)

學校 : 臺北市私立延平高級中學
編號 : 276130
來源 : [203.72.178.1]
最後登入時間 :
2025-07-16 13:08:26

還點進來?

自己寫啦!!!

#46146: Re: c++解答


yp11351205@yphs.tp.edu.tw (809-36黃泊霖)

學校 : 臺北市私立延平高級中學
編號 : 276130
來源 : [203.72.178.1]
最後登入時間 :
2025-07-16 13:08:26

#include <iostream>
#include <vector>
#include <climits> // For INT_MAX

using namespace std;

int matrixChainOrder(const vector<int>& p, int n) {
    vector<vector<int>> dp(n, vector<int>(n, 0)); // dp[i][j] stores minimum multiplication cost

    // l is the chain length
    for (int l = 2; l <= n; l++) {  // l is the length of the chain
        for (int i = 0; i < n - l + 1; i++) {
            int j = i + l - 1;  // j is the end index of the chain
            dp[i][j] = INT_MAX;  // Initialize with a large value
            // Try every possible position to split the chain
            for (int k = i; k < j; k++) {
                int q = dp[i][k] + dp[k+1][j] + p[i] * p[k+1] * p[j+1];
                if (q < dp[i][j]) {
                    dp[i][j] = q;
                }
            }
        }
    }
    return dp[0][n-1];
}

int main() {
    int n;
    cin >> n;
    vector<int> p(n+1);
    for (int i = 0; i <= n; i++) {
        cin >> p[i];
    }

    cout << matrixChainOrder(p, n) << endl;
    return 0;
}