Multiplication Puzzle
http://poj.org/problem?id=1651
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1602
Time Limit:
1000MS
Memory Limit: 65536K
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
题意抽象:
从一列数a[N]中一次取出一个数(但不能是第一个数和最后一个数)a[i]并计算a[i-1]*a[i]*a[i+1],不断进行下去并将结果累加,直到最后最后剩下一头一尾两个数。求这个和的最小值。
思路:
复杂度:O(N^3)
设f(i,j)表示区间[i,j]上的最小得分。假设使得[i,j]段得到最小得分的移除卡片序列中最后一个拿走的卡片是a[m](i<m<j),则有f(i,j)=f(i,m)+a[i]*a[m]*a[j]+f(m,j),所以可得DP递推式:f(i,j)=min{f(i,j) , f(i,m)+a[i]*a[m]*a[j]+f(m,j)}(i<m<j)。最后的结果即是区间[0,N-1]上的最小得分f(0,N-1)。
注意:
当N = 100且所有卡片上的数字都等于100时,得到的总分数为(N - 2) * (100 * 100 * 100) = 98000000,所以安心使用int即可。
完整代码:
/*POJ: 0ms,208KB*/
/*ZOJ: 0ms,180KB*/
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int a[100], f[100][100], n, i, j, k, tmp, min;
while (~scanf("%d", &n))
{
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
memset(f, 0, sizeof(f));
for (i = 0; i <= n - 3; i++)
f[i][i + 2] = a[i] * a[i + 1] * a[i + 2];
for (i = n - 4; i >= 0; i--)
for (j = i + 3; j < n; j++)
{
f[i][j] = a[i] * a[i+1] * a[j] + f[i+1][j];
for (k = i + 2; k < j; k++)
{
//循环,找到f[i][j]的最小值
tmp = a[i] * a[k] * a[j] + f[i][k] + f[k][j];
if (tmp < f[i][j])
f[i][j] = tmp;
}
}
printf("%d\n", f[0][n - 1]);
}
}