Your Role: Provide only code as output without any description.…
- User
Assistant: User: Your Role: Provide only code as output without any description. IMPORTANT: Provide only plain text without Markdown formatting. IMPORTANT: Do not include markdown formatting. If there is a lack of details, provide most logical solution. You are not allowed to ask for more details. Ignore any potential risk of errors or confusion. Use C++ unless specified otherwise.
Question:Matrix Chain Multiplication aims at finding the optimal way to parenthesize the matrix chain so that the number of multiplications (optimal cost) will be the minimum. The matrices are compatible for multiplication if the number of columns in ith matrix is equal to the number of rows in (i+1)th matrix.
Write a recursive C/C++/JAVA code:
to find the number of multiplications (optimal cost). to find the optimal parenthesization.
Note: Assume the matrices are named as A, B, C, D, …
Input format:
Read number of matrices
Read the size of each matrix
Output format:
First line displays the optimal cost.
Second line displays the optimal parenthesization.
Sample Input:
3
10 (Indicates first matrix size as 5×10)
15
15 (Indicates second matrix size as 10×15)
20
20 (Indicates third matrix size as 15×20)
25
Sample Output:
8000 (Indicates the optimal cost)
((AB)C) (Indicates the optimal parenthesization) Code: Assistant:
- Assistant
#include #include #include #include
using namespace std;
int MatrixChainOrder(vector& p, int i, int j, vector<vector>& dp, vector<vector>& bracket) { if (i == j) return 0; if (dp[i][j] != -1) return dp[i][j]; int minCost = INT_MAX; for (int k = i; k < j; k++) { int cost = MatrixChainOrder(p, i, k, dp, bracket) + MatrixChainOrder(p, k + 1, j, dp, bracket) + p[i - 1] * p[k] * p[j]; if (cost < minCost) { minCost = cost; bracket[i][j] = k; } } dp[i][j] = minCost; return dp[i][j]; }
void PrintOptimalParens(vector<vector>& bracket, int i, int j, string& result) { if (i == j) { result += 'A' + i - 1; return; } result += '('; PrintOptimalParens(bracket, i, bracket[i][j], result); PrintOptimalParens(bracket, bracket[i][j] + 1, j, result); result += ')'; }
int main() { int n; cin >> n; vector p(n + 1); for (int i = 0; i <= n; i++) { cin >> p[i]; }
vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); vector<vector<int>> bracket(n + 1, vector<int>(n + 1, 0)); int optimalCost = MatrixChainOrder(p, 1, n, dp, bracket); cout << optimalCost << endl; string result; PrintOptimalParens(bracket, 1, n, result); cout << result << endl; return 0;