动态规划——Poj 1651 Multiplication Puzzle

1)   题目


Multiplication Puzzle

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 4948

 

Accepted: 2958

Description

The multiplication puzzle is played with arow of cards, each containing a single positive integer. During the move playertakes one card out of the row and scores the number of points equal to theproduct of the number on the card taken and the numbers on the cards on theleft and on the right of it. It is not allowed to take out the first and thelast 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 ofscored points. 

For example, if cards in the row contain numbers 10 1 50 20 5, player mighttake 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, thescore would be 

1*50*20 + 1*20*5 + 10*1*5 = 1000+100+50 =1150.

Input

The first line of the input contains thenumber of cards N (3 <= N <= 100). The secondline contains N integers in the range from 1 to 100, separated by spaces.

Output

Output must contain a single integer - theminimal score.

Sample Input

6

10 1 50 50 20 5

Sample Output

3650


2)    题意

有N张写有数字的卡片排成一行,按一定次序从中拿走N-2张(第1张和最后一张不能拿),每次只拿一张,取走一张卡片的同时,会得到一个分数,分值的计算方法是:要拿的卡片,和它左右两边的卡片,这三张卡片上数字的乘积。按不同的顺序取走N-2张卡片,得到的总分可能不相同,求出给定一组卡片按上述规则拿取的最小得分。


3)    数据范围

卡片的数量N(3<= N <= 100),卡片上的数字M(1<= M <= 100)。

给定的一组卡片,不同的拿取方法总共有(N-2)!种。枚举法不可行。

当N = 100,所有卡片上的数字都等于100时,得到的总分数T为:

T = (N-2) * (100 * 100 * 100) = 98000000

所以4字节整形即可存储。


4)    算法

这道题实质上就是矩阵连乘,所以可以使用动态规划法,或者备忘录法。

动态规划——矩阵连乘问题


5)    代码

#include 
#include 
#include 

using namespace std;

#define SIZE 105
#define INF 999999999

int cards[SIZE];
int d[SIZE][SIZE];

int MinScore(int n)
{
	memset(d, 0, sizeof(d));

	int len;
	for (len = 1; len < n; len++)
	{
		int i, j, k;
		for (i = 1, j = len+1; j < n; i++, j++)
		{
			int min = INF;
			for (k = i; k < j; k++)
			{
				int count = d[i][k] + d[k+1][j] + cards[i-1]*cards[k]*cards[j];
				if (count < min)
				{
					min = count;
				}
			}
			d[i][j] = min;
		}
	}
	return d[1][n-1];
}

int main(void)
{
	int ncards;
	while (scanf("%d", &ncards) != EOF)
	{
		int i;
		for (i = 0; i < ncards; i++)
		{
			scanf("%d", &cards[i]);
		}

		printf("%d\n", MinScore(ncards));
	}
	return 0;
}

6)    测试数据


6
10 1 50 50 20 5

7

30 35 15 5 10 20 25

3

1 2 3

100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100

100 100 100 100 100 100 100 100 100 100


7)    提交结果


你可能感兴趣的:(动态规划)