矩陣連乘問題

來源:互聯網
上載者:User

標籤:遞迴   val   end   cto   space   sub   bsp   png   ++   

今天這題困擾了我好久,本來以為是自己dp寫錯了,結果wa了好多次以後發現原來是自己的處理輸入這塊出現了不知名的bug,所以乾脆直接用結構體存了!!!

 

 

思路:動態規劃的典型問題,將矩陣連乘積AiAi-1...Aj簡記為A[i:j] ,i≤j  。

考察計算A[i:j]的最優計算次序。設這個計算次序在矩陣Ak和Ak+1之間將矩陣鏈斷開,i≤k<j,則其相應完全加括弧方式為:

(AiAi+1...Ak)(Ak+1Ak+2...Aj)

令m[i:j]為最優解,則m[i:k]和m[k+1:j]則為A[i:k]和A[k+1:j]的最優解,以此遞迴這得遞迴式:

代碼如下:

 1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 #define INF 999999999 6  7 using namespace std; 8  9 struct M10 {11     int x;12     int y;    13 }m[1010];14 15 int dp[1010][1010];16 int solve(int n)17 {18     memset(dp,0,sizeof(dp));19     for (int len = 2; len <= n; len++)20     {21         for(int i=1; i<=n-len+1; i++)22         {23             int j = i+len-1;24             dp[i][j] = dp[i+1][j] + m[i-1].x*m[i-1].y*m[j-1].y;25             for (int k = i+1; k < j; k++)26             {27                 int count = dp[i][k] + dp[k+1][j] + m[i-1].x*m[k-1].y*m[j-1].y;28                 if (count < dp[i][j])29                     dp[i][j] = count;30             }31         }32     }33     return dp[1][n];34 }35 int main()36 {37     int n;38     while(cin>>n)39     {40         bool falg=false;41         for(int i=0; i<n; i++)42         {43             cin>>m[i].x>>m[i].y;44         }45         for(int i=0; i<n-1; i++)46         {47             if(m[i].y != m[i+1].x)48             {49                 falg = true;50                 break;51             }52         }53         if(!falg)54         {55             cout<<solve(n)<<endl;56         }57         else58             cout<<"invalid argument"<<endl;59         60     }61     return 0;62 }

 

矩陣連乘問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.