Multiplication Puzzle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9500 Accepted: 5906
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
分析
矩阵链(Matrix Chain),用迭代实现动态规划.
我把分析放在了代码注释中
感受
刚开始一直看别人代码,看不懂后来拿纸一步一步算总算弄明白了,Orz看十遍不如亲手算一遍.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
#define inf 0x3fffffff
#define maxn 105
int p[maxn];// 表示矩阵的行数, 注意我是从0开始的
int m[maxn][maxn];//m[i][j]表示从第i个矩阵链到第j个矩阵链的最少相乘次数
int s[maxn][maxn];//s[i][j]表示从第i个矩阵链到第j个矩阵链的分界点(也就是解的追踪),在本题中可以不写
void matrix_chain(int* p,int n,int m[maxn][maxn],int s[maxn][maxn]){
for(int i=0;i<=n;i++)
m[i][i]=0;
for(int len=2;len<n;len++)//len:链长
for(int i=1;i<=n-len+1;i++)// i:左边界 (i=1,表示第i个矩阵链)
{
int j=i+len-1;//通过左边界i和链长r可确定右边界j (j:第j个矩阵链)
m[i][j]=inf;// init
for(int k=i;k<=j-1;k++){
int t=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if( t < m[i][j]){
m[i][j]=t; //更新解
s[i][j]=k;
}
}
}
}
//print_parens的功能是打印括弧,本题可以不要.
//paren : 括弧
//感觉和线段树有点相似,对着样例把这个树画出来就懂了,图在代码的最下面*/
void print_parens(int s[maxn][maxn],int i ,int j)
{
if(i==j)
printf("A%d",i);
else
{
printf("(");
print_parens(s,i,s[i][j]);
print_parens(s,s[i][j]+1,j);//递归调用
printf(")");
}
}
int main(){
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&p[i]);
}
matrix_chain(p,n,m,s);
printf("%d\n",m[1][n-1]);
/*
printf("%d\n",s[1][n-1]);
printf("%d\n",s[2][n-1]);
printf("%d\n",s[2][4]);
printf("\nprint_parens:\n");
print_parens(s,1,n-1);
*/
return 0;
}
关于print_parens的理解
下图是依据样例可以画出的树,然后按照先序遍历访问所有节点.
对于绿色节点:
第一次访问打印左括弧(即入栈时打印“(”) ,第二次访问打印右括弧(即出栈时打印”)”)
对于红色节点:
直接输出Ai
最后打印出的结果为:
(A1(((A2A3)A4)A5))