题目分析
感觉记忆化搜索好写多了,找到递归边界,一会就写出来了,正着推老是因为要用小区间去推大区间,因此计算顺序很重要,很容易写错,但是记忆化搜索就不怎么用担心这个问题。这道题就是矩阵连乘问题的改版,这道题如果想着一个一个删除处理起来及其不方便,因此还是一个一个往里面加简单,很多dp题都是这样正着推不好推,但是倒着推很容易得到答案。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 105;
const int INF = 0x3f3f3f3f;
int a[maxn],dp[maxn][maxn];
int solve(int l,int r){
if(r-l<2)
return dp[l][r] = 0;
if(~dp[l][r]) return dp[l][r];
int ans = INF;
for(int i = l+1; i <= r-1; i++){
int le = solve(l,i);
int ri = solve(i,r);
ans = min(ans, le+ri+a[l]*a[i]*a[r]);
}
return dp[l][r] = ans;
}
int main(){
int n;
while(scanf("%d", &n) != EOF){
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
memset(dp, -1, sizeof(dp));
printf("%d\n", solve(1,n));
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 105;
const int INF = 0x3f3f3f3f;
int a[maxn], dp[maxn][maxn];
int main(){
int n;
while(scanf("%d", &n) != EOF){
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
memset(dp, INF, sizeof(dp));
for(int i = 1; i <= n; i++) dp[i][i] = dp[i][i+1] = 0;
for(int len = 2; len <= n; len++){ //区间长度
for(int i = 1; i + len <= n; i++){ //枚举左端点
int j = i+len; //得出右端点
for(int k = i+1; k < j; k++){ //枚举中间节点
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + a[i]*a[k]*a[j]);
}
}
}
printf("%d\n", dp[1][n]);
}
return 0;
}