UVa 348 Optimal Array Multiplication Sequence(dp)

来源:互联网 发布:php可以做后端吗 编辑:程序博客网 时间:2024/05/01 17:30

题目链接:UVa 348 - Optimal Array Multiplication Sequence

最优矩阵链乘。

状态转移方程:dp[x][y] = min ( dp[x][y], DP(x,i) + DP(i + 1,y) + node[x].x * node[i].y * node[y].y)

难点在于打印,我看了人家的代码才写出来,很精妙。

#include <iostream>#include <cstring>using namespace std;const int MAX_N = 10 + 2;struct Node{    int x,y;};Node node[MAX_N];int dp[MAX_N][MAX_N];int path[MAX_N][MAX_N];int n;int DP(int x,int y){    if(dp[x][y])        return dp[x][y];    for(int i = x;i < y;i++)    {        int temp = DP(x,i) + DP(i + 1,y) + node[x].x * node[i].y * node[y].y;        if(!dp[x][y] || temp < dp[x][y])        {            dp[x][y] = temp;            path[x][y] = i;        }    }    return dp[x][y];}void showPath(int x,int y){    if(x == y)        cout << "A" << x + 1;    else    {        cout << "(";        showPath(x,path[x][y]);        cout << " x ";        showPath(path[x][y] + 1,y);        cout << ")";    }}int main(){    int num = 0;    while(cin >> n,n)    {        memset(dp,0,sizeof(dp));        memset(path,0,sizeof(path));        for(int i = 0;i < n;i++)            cin >> node[i].x >> node[i].y;        DP(0,n - 1);        cout << "Case " << ++num << ": ";;        showPath(0,n - 1);        cout << endl;    }    return 0;}


0 0