Guest User

Accepted Code for MCM

a guest
Jun 27th, 2024
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | Source Code | 0 0
  1. PROBLEM LINK: https://www.geeksforgeeks.org/problems/matrix-chain-multiplication0303/0
  2.  
  3.  
  4.  
  5. class Solution{
  6. public:
  7. long long t[105][105];
  8. long long mxm(int arr[],int i,int j){
  9. if(i>=j){
  10. return 0;
  11. }
  12. if(t[i][j]!=-1){
  13. return t[i][j];
  14. }
  15. long long mn=INT_MAX;
  16. for(int k=i;k<=j-1;k++){
  17. long long left,right;
  18. if(t[i][k]!=-1){
  19. left=t[i][k];
  20. }
  21. else{
  22. left=mxm(arr,i,k);
  23. t[i][k]=left;
  24. }
  25. if(t[k+1][j]!=-1){
  26. right=t[k+1][j];
  27. }
  28. else{
  29. right=mxm(arr,k+1,j);
  30. t[k+1][j]=right;
  31. }
  32. long long temp=left+right+(arr[i-1]*arr[k]*arr[j]);
  33. mn=min(temp,mn);
  34. }
  35. t[i][j]=mn;
  36. return mn;
  37. }
  38. int matrixMultiplication(int N, int arr[])
  39. {
  40. memset(t,-1,sizeof(t));
  41. int ans=mxm(arr,1,N-1);
  42. return ans;
  43. }
  44. };
Tags: Code
Advertisement
Add Comment
Please, Sign In to add comment