zoukankan      html  css  js  c++  java
  • POJ --1651 Multiplication Puzzle

    Multiplication Puzzle
     

    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

    思路:动态规划,不论怎么取则必须有一个最后取(设为k),设dp[n][m] 是n到m这段中的最优解,则dp[n][m] = min(dp[n][k]+dp[k][m]+a[k]*a[n]*a[m],dp[n][m])(k > n && k < m),需要记忆化搜索(即,一旦dp[n][m]已被搜到过直接返回),通过递归求解下一状态,再回溯到当前最优解。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<string>
     4 #include<cstring>
     5 #define MAXN 111
     6 #define INF 0x7fffffff
     7 #define LL long long
     8 using namespace std;
     9 LL dp[MAXN][MAXN];
    10 int a[MAXN];
    11 LL dfs(int n,int m){
    12     if(dp[n][m] != INF) return dp[n][m];
    13     if(n == m-2) return dp[n][m] = a[n]*a[n+1]*a[n+2];
    14     if(n == m-1) return dp[n][m] = 0;
    15     for(int i = n+1;i <= m-1;i ++) dp[n][m] = min(dfs(n,i)+dfs(i,m)+a[i]*a[n]*a[m],dp[n][m]);
    16     return dp[n][m];
    17 
    18 }
    19 int main(){
    20     int n;
    21     while(~scanf("%d",&n)){
    22         for(int i = 0;i < n;i ++)
    23             for(int j = 0;j < n;j ++) dp[i][j] = INF;
    24         for(int i = 0;i < n;i ++) scanf("%d",a+i);
    25         printf("%lld
    ",dfs(0,n-1));
    26     }
    27     return 0;
    28 }
     
  • 相关阅读:
    人为什么会生气 --- 答案是什么?
    职场中我们常犯的8个错误
    职场上最常见的20条错误,犯三条就够致命啦
    C语言,基于单向链表实现,变长动态数据缓冲区(线程安全) ---- 类似java的StringBuffer --- 亲测OK
    门限签名
    基于RSA的实用门限签名算法
    图解密码技术(第3版)-第4章
    各种加密算法比较
    密码那点事儿
    数字签名,我有疑问。
  • 原文地址:https://www.cnblogs.com/anhuizhiye/p/3678883.html
Copyright © 2011-2022 走看看