poj-1651-Multiplication Puzzle--区间DP
Posted zhang--yd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj-1651-Multiplication Puzzle--区间DP相关的知识,希望对你有一定的参考价值。
poj-1651-Multiplication Puzzle--区间DP
Multiplication Puzzle
Description 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 If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be 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 Source Northeastern Europe 2001, Far-Eastern Subregion
|
1651 | Accepted | 508K | 0MS | G++ | 764B | 2017-09-16 15:26:12 |
对于这种区间DP问题,主要是写对DP方程式。开始写成 dp[i][j] = dp[i][k-1] + num[k-1]*num[k]*num[k+1] + dp[k+1][j] . 明显是没有理解题意。
将该num[k] 给取出之后, num[k-1] 和 num[k+1] 成为相邻的,所以:
不应该是需要从后面逆推,即是 dp[i][j] = dp[i][k] + dp[k][j] + num[i]*num[j]*num[k] . 可以从三个数字,四个数字这样试下。
#include <cstdio> #include <cstring> #define min(a, b) (a)>(b)?(b):(a) const int MAXN = 110; int n, num[MAXN]; long long dp[MAXN][MAXN]; long long Solve(int l, int r){ if(dp[l][r] != 0x3f3f3f3f3f3f){ return dp[l][r]; } if(l + 1 >= r){ dp[l][r] = 0; return 0; } for(int i=l+1; i<r; ++i){ long long tmp = num[l]*num[i]*num[r]; dp[l][r] = min(dp[l][r], tmp + Solve(l, i) + Solve(i, r)); } return dp[l][r]; } int main(){ freopen("in.txt", "r", stdin); long long ans; while(scanf("%d", &n) != EOF){ for(int i=0; i<n; ++i){ scanf("%d", &num[i]); } for(int i=0; i<n; ++i){ for(int j=0; j<n; ++j){ dp[i][j] = 0x3f3f3f3f3f3f; } } // memset(dp, 0x3f3f3f3f, sizeof(dp)); ans = Solve(0, n-1); printf("%lld\n", ans ); } return 0; }
以上是关于poj-1651-Multiplication Puzzle--区间DP的主要内容,如果未能解决你的问题,请参考以下文章
POJ - 1651 Multiplication Puzzle
题解POJ1651Multiplication Puzzle
poj-1651-Multiplication Puzzle--区间DP
POJ 1651 Multiplication Puzzle (区间DP)