Multiplication Puzzle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9677 Accepted: 6013
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
为了学习dp来拿这道题练练手
先是试了试dfs穷举:
#include <iostream>
using namespace std;
int mins = 200000000;
int a[100+10];
void dfs(int *p,int n,int s,int cur)
{
if(s>mins)
return;
if(cur==n-2)
{
if(s<mins)
mins = s;
return;
}
int l=1,r=n-2,i;
while(p[l]==0) l++;
while(p[r]==0) r--;
for(i=l;i<=r;i++)
{
if(p[i]==1)
{
p[i] = 0;
int ll=i,rr=i;
while(p[ll]==0) ll--;
while(p[rr]==0) rr++;
dfs(p,n,s+a[i]*a[ll]*a[rr],cur+1);
p[i] = 1;
}
}
}
int main()
{
int n,i;
int p[100+10];
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
p[i] = 1;
}
dfs(p,n,0,0);
cout<<mins<<endl;
return 0;
}
然后果不其然超时了。。。
所以还是dp吧,写了两种形式,个人感觉第二种更加清楚易懂
#include <iostream>
#include <cstring>
using namespace std;
int d[105],dp[105][105];
int main()
{
int n,i,l,j,t,s;
cin>>n;
for(i=0;i<n;i++)
cin>>d[i];
memset(dp,0,sizeof(dp));
for(l=2;l<n;l++)
{
for(i=0;i+l<n;i++)
{
t = 1000000000;
for(j=i+1;j<i+l;j++)
{
s = dp[i][j]+dp[j][i+l]+d[i]*d[j]*d[i+l];
if(s<t)
t = s;
}
dp[i][i+l] = t;
}
}
cout<<dp[0][n-1]<<endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int d[105],dp[105][105];
int work(int l,int r)
{
if(r-l<2)
return dp[l][r] = 0;
if(dp[l][r]!=-1)
return dp[l][r];
if(r-l==2)
return dp[l][r] = d[l]*d[l+1]*d[l+2];
int t = 1000000000,s;
for(int k=l+1;k<r;k++)
{
s = work(l,k)+work(k,r)+d[l]*d[k]*d[r];
if(s<t)
t = s;
}
return dp[l][r] = t;
}
int main()
{
int n,i;
cin>>n;
for(i=0;i<n;i++)
cin>>d[i];
memset(dp,-1,sizeof(dp));
cout<<work(0,n-1)<<endl;
return 0;
}