Question link: https://www.tyvj.cn/Problem_Show.aspx? Id = 1014
BACKGROUND Background
Taiyuan Chengcheng Middle School No. 4 in the 2nd simulation Competition
Description
The multiplication game is played on a row of cards. Each card contains a positive integer. In each movement, the player takes out a card, and the score is multiplied by its number on the left and right. Therefore, 1st cards and the last card are not allowed. After the last move, there are only two cards left.
Your goal is to minimize the sum of scores.
For example, if the number is 10 1 50 20 5, take 1, 20, 50 in sequence, and the total score is 10*1*50 + 50*20*5 + 10*50*5 = 8000
Take 50, 20, 1, and the total score is 1*50*20 + 1*20*5 + 10*1*5 = 1150.
Input Format
The first line of mul. In the input file contains the number of cards (3 <= n <= 100), and the second line contains N 1-100 integers separated by spaces.
Output Format
Output file Mul. Out has only one number: Minimum score
Sample Input
Sample output sample output
Time Limit
1 s for each test point
[Analysis]
Memory-based search DP
F [I] [J] indicates the minimum value obtained by the interval [I, j. F [I, j]: = min (F [I, K] + F [K, J] + A [I] * A [k] * A [J]) where I <k <j. (K indicates the interval [I, j]. The K card is used for the last time)
Continuously divide intervals and save the results.
#include <cstdio>#include <cstdlib>#include <algorithm>using namespace std;long long int f[101][101];int a[101], i, j, n, INF=0x7f7f7f7f;void dfs(int l, int r) { if(r-l<=1) {f[l][r]=0; return;} if(f[l][r]!=INF) return; for(int i=l+1;i<=r-1;++i) dfs(1,i),dfs(i,r),f[l][r]=min(f[l][r],f[l][i]+f[i][r]+a[i]*a[l]*a[r]);}int main(void) { freopen("in1.txt","r",stdin); scanf("%d",&n);for(i=1;i<=n;scanf("%d",a+i++)) ;for(i=0;i<=n;++i)for(j=0;j<=n;++j)f[i][j]=INF;dfs(1,n);printf("%lld\n",f[1][n]); return 0;}
Or:
1 var 2 i,j,k,l,n:longint; 3 f:array[1..100,1..100]of longint; 4 num:array[1..100]of longint; 5 6 7 begin 8 readln(n); 9 for i:=1 to n do10 read(num[i]);11 12 for l:=1 to n do13 for i:=1 to n-l+1 do14 begin15 j:=i+l+1;16 f[i,j]:=MaxLongint;17 for k:=i+1 to j-1 do18 if f[i,k]+f[k,j]+num[i]*num[k]*num[j]<f[i,j] then19 f[i,j]:=f[i,k]+f[k,j]+num[i]*num[k]*num[j];20 end;21 22 writeln(f[1,n]);23 24 end.
Tyvj1014-multiplication game