ZOJ 1602 Multiplication Puzzle(区间DP)题解

题意:n个数字的串,每取出一个数字的代价为该数字和左右的乘积(1、n不能取),问最小代价

思路:dp[i][j]表示把i~j取到只剩 i、j 的最小代价。

代码:

#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
const int maxn = 100 + 10;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int dp[maxn][maxn], a[maxn];
int main(){
    int n;
    while(~scanf("%d", &n)){
        for(int i = 1; i <= n; i++){
            scanf("%d", &a[i]);
        }
        memset(dp, INF, sizeof(dp));
        for(int i = 1; i + 1 <= n; i++){
            dp[i][i + 1] = 0;
        }
        for(int len = 3; len <= n; len++){
            for(int i = 1; i + len - 1 <= n; i++){
                int j = i + len - 1;
                for(int k = i + 1; k < j; k++){
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + a[i] * a[j] * a[k]);
                }
            }
        }
        printf("%d\n", dp[1][n]);
    }
    return 0;
}

 

Multiplication Puzzle

 ZOJ - 1602

posted @ 2019-01-25 17:36  KirinSB  阅读(140)  评论(0编辑  收藏  举报