最优矩阵连乘

由于我不会矩阵,所以这道DP我是根据方程直接写的。

f(i,j) = min(f(i,k) + f(k + 1, j) + a[i - 1] * a[k] * a[j])

在实现技巧上应用了记忆化搜索。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 105, inf = 1e9;

int n; 

int a[maxn], vis[maxn][maxn], c[maxn][maxn];

int dp(int x, int y)
{
    if (vis[x][y]) return c[x][y];
    vis[x][y] = 1;
    int& ans = c[x][y];//这是之前讲过的套路
    if (x == y) return ans = 0;
//    ans = dp(x + 1, y)  +a[x - 1] * a[x] * a[y];
    ans = inf;
    for (int i = x; i < y; i++) 
    {
        int t1 = dp(x, i);
        int t2 = dp(i + 1, y);
        ans = min(ans, t1 + t2 + a[x - 1] * a[i] * a[y]);
    } 
    return ans;
}

int main()
{
//    freopen("最优矩阵连乘.in","r",stdin);
    scanf("%d", &n);
    for (int i = 0; i <= n; i++)
        scanf("%d", &a[i]);
    memset(vis, 0, sizeof vis);
    printf("%d", dp(1, n));
    return 0;
}
原文地址:https://www.cnblogs.com/yohanlong/p/7722123.html