POJ 1651

Multiplication Puzzle
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4991   Accepted: 2979

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 
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.

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
这道题是典型的矩阵连乘 , 题目要求给你一列n个数,除了第一个和最后一个数,按照一定顺序,取一个数和他的左右两数相乘,然后干掉这个数,直到整个数列只剩下第一个和最后一个 , 求这些乘积之和最小是多少。
n个数的连乘可以转化成n - 1个矩阵的连乘。
矩阵连乘不会的可以看这里 http://www.cnblogs.com/liushang0419/archive/2011/04/27/2030970.html
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int m[105][105],p[105];
int n;
int ans(int n)
{
    n -= 1;
    for(int i = 1 ; i <= n ; i++ )
    {
        m[i][i] = 0;
    }
    for(int r = 2 ; r <= n ; r++)
    {
        for(int i = 1 ; i <= n + 1 - r ; i++)
        {
            int j = i + r - 1;
            m[i][j] = 1 << 30;
            for(int k = i ;k < j ; k++)
            {
                int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[j] * p[k];
                if(q < m[i][j])
                {
                    m[i][j] = q;
                }
            }
        }
    }
    return m[1][n];
}
int main()
{
    //freopen("in.txt" , "r" , stdin);
    while(scanf("%d",&n)!=EOF)
    {
        memset(m , 0 , sizeof(m));
        memset(p , 0 , sizeof(p));
        for(int i = 0 ; i < n ; i++)
        {
            scanf("%d",&p[i]);
        }
        printf("%d\n",ans(n));
    }
    return 0;
}
/*



*/


你可能感兴趣的:(dp,ACM)