原题:
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 10*1*50 + 50*20*5 + 10*50*5 = 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
1*50*20 + 1*20*5 + 10*1*5 = 1000+100+50 = 1150
输入,输出
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 must contain a single integer - the minimal score.
AC代码
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAX_N = 100 + 1;
int dp[MAX_N][MAX_N];
int Q[MAX_N],N;
const int INF = 1e9;
void solve()
{
for( int i = 2; i < N; i++ )
for( int j = 0; j + i < N; j++ )
{
dp[j][j + i] = INF;
for( int k = j + 1; k < j + i; k++ )
{
dp[j][j + i] = min( dp[j][j + i],
dp[j][k] +
dp[k][i + j] +
Q[k] * Q[j] * Q[j + i] );
}
}
printf( "%d\n",dp[0][N-1] );
}
int main()
{
while( ~scanf( "%d",&N ) )
{
memset( dp,0,sizeof( int ) * MAX_N * MAX_N );
for( int i = 0; i < N; i++ )
scanf( "%d",Q + i );
solve( );
}
return 0;
}
解题思路:
假设一组数字为A1,A2,A3…An.
考虑最后的状态A1,Ai,An
这说明1->i 和 i->n 之间的数都已经被拿完了,所以如果知道了1->i and i->n之间的最小值,整个问题的答案也就出来了
即 dp[ 1 ][ n ] = dp[ 1 ][ i ] + dp[ i ][ n ]
同理 dp[ 1 ][ i ] = dp[ 1 ][ j ] + dp[ j ][ i ] , dp[ i ][ n ] = dp[ i ][ k ] + dp[ k ][ n ]
所以我们从长度最小也就是 3 的区间开始计算,便能推出最终的答案,而且每个区间只计算了一次,从上面的代码不难看出复杂度为O( N^3 )