Guest User

TLE code for MCM

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