1651 Multiplication Puzzle [ 區間dp ]
Problem Describe
The multiplication puzzle is played with a row of cards, each containing a single positive integer. During the move player takes one card out of the row and scores the number of points equal to the product of the number on the card taken and the numbers on the cards on the left and on the right of it. It is not allowed to take out the first and the last card in the row. After the final move, only two cards are left in the row.
The goal is to take cards in such order as to minimize the total number of scored points.
For example, if cards in the row contain numbers 10 1 50 20 5, player might take a card with 1, then 20 and 50, scoring
10150 + 50205 + 10505 = 500+5000+2500 = 8000
If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
150
Input
The first line of the input contains the number of cards N (3 <= N <= 100). The second line contains N integers in the range from 1 to 100, separated by spaces.
Output
Output must contain a single integer - the minimal score.
Sample Input
6
10 1 50 50 20 5
Sample Output
3650
題意 : 給出N個元素,第一個和第n個不能選,每次選擇第k個,獲得點數 a[k]=a[k-1]*a[k]*a[k+1],選到只剩第一個和最後一個為止。求最小點數
思路 : 區間dp ,令 dp[i][j]代表區間 i -> j 的最小值 那麼對於區間 i -> j
dp[i][j] = min(dp[i][j] ,dp[i][k] + dp[k][j] + v[i] * v[j] * v[k] );
AC code :
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e3+50;
const int inf = 0x3f3f3f3f;
ll dp[maxn][maxn] ,v[maxn] ;
int n ;
int main() {
while(~scanf("%d",&n)) {
for (int i = 1;i<=n;i++) scanf("%lld",&v[i]);
memset(dp ,0 ,sizeof(dp) );
for (int i = 1 ; i <= n - 2 ; i ++) {
dp[i][i+2] = v[i] * v[i+1] * v[i+2] ;
}
for (int l = 4 ; l <= n ; l ++ ) {
for (int i = 1 ; i <= ( n - l + 1 ) ; i ++ ) {
int j = i + l - 1 ;
dp[i][j] = inf ;
for (int k = i + 1 ;k <= j - 1 ; k ++ ) {
dp[i][j] = min(dp[i][j] ,dp[i][k] + dp[k][j] + v[i] * v[j] * v[k] ) ;
}
}
}
printf("%lld\n",dp[1][n]);
}
return 0;
}