zoukankan      html  css  js  c++  java
  • 挑战程序设计2 矩阵链乘

    Matrix Chain Multiplication

    Time Limit : 1 sec, Memory Limit : 65536 KB 
    Japanese version is here

    Matrix-chain Multiplication

    The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given nnmatrices M1,M2,M3,...,MnM1,M2,M3,...,Mn.

    Write a program which reads dimensions of MiMi, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication M1M2...MnM1M2...Mn.

    Input

    In the first line, an integer nn is given. In the following nn lines, the dimension of matrix MiMi (i=1...ni=1...n) is given by two integers rr and cc which respectively represents the number of rows and columns of MiMi.

    Output

    Print the minimum number of scalar multiplication in a line.

    Constraints

    • 1n1001≤n≤100
    • 1r,c1001≤r,c≤100

    Sample Input 1

    6
    30 35
    35 15
    15 5
    5 10
    10 20
    20 25
    

    Sample Output 1

    15125

    AC代码:
    #define _CRT_SECURE_NO_DEPRECATE
    #include<iostream>
    #include<cstdio>
    #include<vector>
    #include<algorithm>
    #include<cstring>
    #include<set>
    #include<string>
    #include<queue>
    #include<cmath>
    using namespace std;
    #define INF 0x3f3f3f3f
    const int N_MAX = 200;
    int n;
    int dp[N_MAX][N_MAX];
    int p[N_MAX];
    
    void solve() {
        for (int i = 1; i <= n;i++) {
            dp[i][i] = 0;
         }
        for (int l = 2; l <= n;l++) {//区间长度由2开始增长
            for (int i = 1; i <= n - l + 1;i++) {
                int j = i + l - 1;//[i,j]为当前需要考虑的区间
                dp[i][j] = INF;
                for (int k = i; k <= j - 1;k++) {//!!!!!
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]);
                }
            }
        }
        cout << dp[1][n] << endl;
    }
    
    int main() {
        while (scanf("%d",&n)!=EOF) {
            for (int i = 1; i <= n;i++) {
                scanf("%d%d",&p[i-1],&p[i]);
            }
            solve();
        }
        return 0;
    }
  • 相关阅读:
    八、JVM视角浅理解并发和锁
    七、JVM类加载机制
    六、JVM命令和工具
    五、jvm垃圾回收3(几种垃圾收集器)
    四、JVM垃圾回收2(垃圾收集算法)
    jvm引用类型
    三、JVM垃圾回收1(如何寻找垃圾?)
    【原创】Android 对话框的使用
    【原创】CMD常用命令:解决实际问题
    【原创】开机出现grub rescue,修复办法
  • 原文地址:https://www.cnblogs.com/ZefengYao/p/7751644.html
Copyright © 2011-2022 走看看