zoukankan      html  css  js  c++  java
  • 矩阵连乘问题

     

    Description

       一个n*m矩阵由n行m列共n*m个数排列而成。两个矩阵A和B可以相乘当且仅当A的列数等于B的行数。一个N*M的矩阵乘以一个M*P的矩阵等于一个N*P的矩阵,运算量为n*m*p。
      矩阵乘法满足结合律,A*B*C可以表示成(A*B)*C或者是A*(B*C),两者的运算量却不同。例如当A=2*3 B=3*4 C=4*5时,(A*B)*C=64而A*(B*C)=90。显然第一种顺序节省运算量。
      现在给出N个矩阵,并输入N+1个数,第i个矩阵是a[i-1]*a[i]

    Input

    第一行n(n<=100)
    第二行n+1个数 

    Output

    最优的运算量

    Sample Input

    3
    2 3 4 5

    Sample Output

    64

    区间dp

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <iostream>
     4 #include <string>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <vector>
     8 #include <queue>
     9 #include <set>
    10 #include <stack>
    11 #include <map>
    12 #include <sstream>
    13 const int INF=0x3f3f3f3f;
    14 typedef long long LL;
    15 const int mod=1e9+7;
    16 const int maxn=1e5+10;
    17 using namespace std;
    18  
    19 int a[105];//记录矩阵信息 
    20 int dp[105][105];//dp[i][j]表示矩阵i连乘到j的最优解 
    21  
    22 int main()
    23 {
    24     int n;
    25     scanf("%d",&n);
    26     for(int i=1;i<=n+1;i++)
    27     {
    28         scanf("%d",&a[i]);
    29         if(i!=n+1)
    30             dp[i][i]=0;
    31     }
    32     for(int i=1;i<=n-1;i++)//i为长度 
    33     {
    34         for(int j=1;j<=n-i;j++)//j为起始点 
    35         {
    36             int t=INF;
    37             for(int k=j;k<=j+i-1;k++)//k为分割点 
    38                 t=min(t,dp[j][k]+dp[k+1][j+i]+a[j]*a[k+1]*a[j+i+1]);
    39             dp[j][j+i]=t;
    40         }
    41     }
    42     printf("%d
    ",dp[1][n]);
    43     return 0;
    44 }
  • 相关阅读:
    页面引入js问题
    python之循环语句与注释
    python之字符串格式化方法
    python之对象的方法
    python之函数
    python之条件判断
    python之布尔表达式
    python之列表与元组
    python之字符串
    搞不明白的recycling process 和 finalization process
  • 原文地址:https://www.cnblogs.com/jiamian/p/11995121.html
Copyright © 2011-2022 走看看