zoukankan      html  css  js  c++  java
  • POJ-1651 Multiplication Puzzle 【区间DP】

    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。
    f(i,j)代表i~j区间的minimal score,即把i+1~j-1的数字都抽走了剩下i和j两张牌。
    因而转移方程为:
      f(i,j) = min(f(i,j), f(i,k)+f(k,j)+ai*ak*aj);
    最终状态为f(1,n)

    Code:
     1 #include<cstdio>
     2 #include<iostream>
     3 #include<algorithm>
     4 #include<cstring>
     5 #include<set>
     6 #include<queue>
     7 #include<string>
     8 using namespace std;
     9 const int maxn = 100 + 5;
    10 int f[maxn][maxn], a[maxn];
    11 
    12 int main() {
    13     int n;
    14     while (cin >> n) {
    15         memset(f, 0, sizeof(f));
    16         for (int i = 1; i <= n; ++i) cin >> a[i];
    17         for (int l = 3; l <= n; ++l)
    18             for (int i = 1; i + l - 1 <= n; ++i) {
    19                 int j = i + l - 1;
    20                 f[i][j] = f[i][i+1] + f[i+1][j] + a[i] * a[i+1] * a[j];
    21                 for (int k = i; k < j; ++k)
    22                     f[i][j] = min(f[i][j], f[i][k] + f[k][j] + a[i] * a[k] * a[j]);
    23             }
    24         cout << f[1][n] << endl;
    25     }
    26 
    27     return 0;
    28 }
  • 相关阅读:
    【2021-06-14】何太第一次喝断片
    【2021-06-13】管理的目标也就是把事情做好
    判断字符串的两半是否相等
    生成每种字符都是奇数个的字符串
    叶子相似的树
    面试准备
    北京旅行计划
    M笔试
    连续字符
    字符串中第一个唯一字符
  • 原文地址:https://www.cnblogs.com/robin1998/p/6590520.html
Copyright © 2011-2022 走看看