矩阵连乘问题
区间合并 dp[i][j] = min(dp[i][k] + dp[k+1][j] + p[i-1]*p[k]*p[j]) { i<=k<j }
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N = 10; const ll INF = 1e18; ll dp[N][N], p[N]; int s[N][N]; void dfs(int i,int j) { if(i == j) return ; dfs(i,s[i][j]); dfs(s[i][j]+1,j); printf("[A(%d,%d) A(%d,%d)]\n",i,s[i][j],s[i][j]+1,j); } int main () { int n = 5; p[0] = 20; p[1] = 30; p[2] = 50; p[3] = 10; p[4] = 35; p[5] = 25; memset(dp, 0, sizeof(dp)); for(int len=2; len<=n; len++) { for(int i=1; i+len-1<=n; i++) { int j = i+len-1; dp[i][j] = INF; for(int k=i; k<j; k++) { ll ans = dp[i][k] + dp[k+1][j] + 1LL*p[i-1]*p[k]*p[j]; dp[i][j] = min(dp[i][j], ans); if(dp[i][j] == ans) { s[i][j] = k; } } } } for(int i=1;i<=n;i++) { for(int j=i;j<=n;j++) { printf("%lld ", dp[i][j]); } puts(""); } printf("%lld\n", dp[1][n]); dfs(1, n); return 0; }