The teachers of SMIE are all playing games. XM also want to play so he invents a game. The game is also about stones. At the beginning of the game, XM has N stones in a line. Each stone has its value value[i]. The game has N turns and in each turn XM takes one stone away. The stones are indexed from 0 to N-1. And each time XM takes a stone then he will get some score. If he takes the ith stones, he will get value[i-1]*value[i]*value[i+1]. You can consider value[-1] and value[n] are both 1. And if the ith stone are taken, the i-1th stone and the i+1th stone become adjacent. Now XM wants to get the maximum score and he assigns the work calculating the maximum score to you. You cannot refuse. You are intelligent enough to solve the problem.
The input has several test cases.
The first line contains one integer N (1<=N<=500), representing the stone number. The next line is N number represents the values of stones, which are all in the range of [1, 100]
For each test case, you should output n integer represents the maximum score.
4 3 1 5 8
167
#include <cstdio> #include <iostream> #include <cstring> using namespace std; int a[505]; int dp[505][505]; /* dp[i][j] := 删除掉从i~j的序列的最高得分 假设,最后一个删掉的是第 k个元素 dp[i][j] = dp[i][k-1] + dp[k+1][j] + a[i-1]*a[k]*a[j+1] (当i < j时,其中 i <= k <= j) dp[i][j] = a[i-1]*a[i]*a[i+1] (当 i == j 时) */ int main () { int n; while(scanf("%d", &n) != EOF) { for(int i=1; i<=n; i++) { scanf("%d", &a[i]); } a[0] = a[n+1] = 1; for(int i=1; i<=n; i++) { dp[i][i]=a[i-1]*a[i]*a[i+1]; } for(int step=1; step<n; step++) { for(int i=1; i+step<=n; i++) { int j = i+step; dp[i][j] = 0; for(int k=i; k<=j; k++) { dp[i][j] = max(dp[i][j], dp[i][k-1] + dp[k+1][j] + a[i-1]*a[k]*a[j+1]); } } } printf("%d\n", dp[1][n]); } return 0; }