POJ 1651 Multiplication Puzzle interval DP

 

Meaning of the questions:

Given a string of numbers, take all the required number of intermediate, such that the minimum cost. Which took a digital price for this figure and it is about the product.

solution:

Consider writing regular intervals DP, the interval length enumeration, enumeration starting point, enumerate the split point (the split point here was a section in which last took a number! Is probably the only point to consider this question)

Set DP [i] [j] indicates that all numbers i and j take a minimum cost, a [i] represents the number of position i.

dp[i][j]=min(dp[i][k-1]+dp[k+1][j]+a[i-1]*a[k]*a[j+1])(k=i...j-1)

Because it is considered the minimum, so the array require pretreatment, pretreatment as follows:

dp[i][i-1]=0;

dp[i][i]=a[i]*a[i+1]*a[i-1]

Other dp [i] [j] = INF;

Code:

 

#include <iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
using namespace std;
const int N = 105;
int dp[N][N];
int a[N];
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i<n; i++) {
        scanf("%d", &a[i]);
    }
    
    memset(dp, 0x3f, sizeof(dp));
    for (int i = 1; i < n; i++)
        dp[i][i - 1] = 0;
    for (int i = 1; i < n - 1; i++) {
        dp[i][i] = a[i] * a[i - 1] * a[i + 1];
    }
    for (int len = 1; len <= n - 2; len++) {
        for (int i = 1; i + len - 1<n - 1; i++) {
            int end = i + len - 1;
            for (int k = i; k<=end; k++){
                dp[i][end] = min(dp[i][end], dp[i][k-1]+ dp[k + 1][end] + a[k] * a[i - 1] * a[end + 1]);
            }
        }
    }
    printf("%d\n", dp[1][n - 2]);
    return 0;
}

 

 

 

 

Guess you like

Origin www.cnblogs.com/gzr2018/p/11404177.html