Topic Portal
1 /*2 Test Instructions: Add appropriate parentheses to change the order of calculations to minimize the total number of calculations3 matrix multiplication problem, DP solution: state transition equation:4 Dp[i][j] = min (Dp[i][k] + dp[k+1][j] + p[i-1] * p[k] * p[j]) (I<=K<J)5 S[i][j] Record the location of the break (that is, the position of the parentheses), the backtracking output results6 */7#include <cstdio>8#include <cstring>9#include <string>Ten#include <algorithm> One#include <cmath> A#include <iostream> - using namespacestd; - the Const intMAXN = 1e2 +Ten; - Const intINF =0x3f3f3f3f; - intDP[MAXN][MAXN]; - intS[MAXN][MAXN]; + intP[MAXN]; - intN; + A voidPrintintIintj) at { - if(i = = j) printf ("a%d", i); - Else - { -printf ("("); - print (i, s[i][j]); inprintf ("x"); -Print (S[i][j] +1, j); toprintf (")"); + } - } the * voidWorkvoid) $ {Panax Notoginseng for(intI=1; i<=n; ++i) Dp[i][i] =0; - for(intL=2; l<=n; ++l) the { + for(intI=1; i<=n-l+1; ++i) A { the intj = i + L-1; +DP[I][J] =INF; - for(intK=i; k<=j-1; ++k) $ { $ intTMP = Dp[i][k] + dp[k+1][J] + p[i-1] * P[k] *P[j]; - if(TMP <Dp[i][j]) - { theDP[I][J] = tmp; S[I][J] =K; - }Wuyi } the } - } Wu -Print (1, n); Puts (""); About } $ - intMainvoid)//ZOJ 1276 Optimal Array multiplication Sequence - { - //freopen ("zoj_1276.in", "R", stdin); A + intCAS =0; the while(SCANF ("%d", &n) = =1) - { $ if(n = =0) Break; the for(intI=1; i<=n; ++i) scanf ("%d%d", &p[i-1], &p[i]); the theprintf ("Case %d:", ++CAs); the Work (); - } in the return 0; the } About the /* the Case 1: (A1 x (A2 x A3)) the Case 2: ((A1 x A2) x A3) + Case 3: ((A1 x (A2 x A3)) x ((A4 x A5) x A6)) - */
Matrix Continuous Product ZOJ 1276 Optimal Array multiplication Sequence