Matrix Chain Multiplication

本文介绍了一种通过解析表达式来确定矩阵乘法最优计算顺序的方法,并使用栈来实现算法。通过对输入表达式的分析,算法能够高效地计算所需的最少基本乘法次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Problem Description
Matrix multiplication problem is a typical example of dynamical programming.

Suppose you have to evaluate an expression like A*B*C*D*E where A,B,C,D and E are matrices. Since matrix multiplication is associative, the order in which multiplications are performed is arbitrary. However, the number of elementary multiplications needed strongly depends on the evaluation order you choose.
For example, let A be a 50*10 matrix, B a 10*20 matrix and C a 20*5 matrix.
There are two different strategies to compute A*B*C, namely (A*B)*C and A*(B*C).
The first one takes 15000 elementary multiplications, but the second one only 3500.

Your job is to write a program that determines the number of elementary multiplications needed for a given evaluation strategy.
 

Input
Input consists of two parts: a list of matrices and a list of expressions.
The first line of the input file contains one integer n (1 <= n <= 26), representing the number of matrices in the first part. The next n lines each contain one capital letter, specifying the name of the matrix, and two integers, specifying the number of rows and columns of the matrix.
The second part of the input file strictly adheres to the following syntax (given in EBNF):

SecondPart = Line { Line } <EOF>
Line = Expression <CR>
Expression = Matrix | "(" Expression Expression ")"
Matrix = "A" | "B" | "C" | ... | "X" | "Y" | "Z"
 

Output
For each expression found in the second part of the input file, print one line containing the word "error" if evaluation of the expression leads to an error due to non-matching matrices. Otherwise print one line containing the number of elementary multiplications needed to evaluate the expression in the way specified by the parentheses.
 

Sample Input
  
9 A 50 10 B 10 20 C 20 5 D 30 35 E 35 15 F 15 5 G 5 10 H 10 20 I 20 25 A B C (AA) (AB) (AC) (A(BC)) ((AB)C) (((((DE)F)G)H)I) (D(E(F(G(HI))))) ((D(EF))((GH)I))
 

Sample Output
  
0 0 0 error 10000 error 3500 15000 40500 47500 15125
 

Source



分析:
         借看刘汝佳老师的那本算法书上的对该题的分析如下:      本体的关键就是解析表达式。本体的表达式比较简单,可以用一个栈来完成,遇到字母时入栈,遇到右括号时出栈并计算,然后结果入栈。因为输入保证核发,括号无需入栈。
        例:A是50*10   B是10*20,  C是20*5的,则(A(BC))的乘法次数为10*20*5(BC的乘法次数)+50*10*5(A(BC)的乘法次数)=3500.。
      另外知识点:
        函数名称                                                                                      函数功能
         isalpha                                                                             检查元素是否为字母
         isdigt                                                                                检查元素是否为梳子(0~9)
         islower                                                                             检查元素是否为小写字母
         isalnum                                                                            检查元素是否为字母或数字
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;

struct Matrix{//定义矩阵类型的结构体 
  int a,b;
  Matrix(int a=0,int b=0):a(a),b(b){
  }
}m[26];//结构体数组 

stack<Matrix>s;//运用到栈的知识; 


int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		string name;
		cin>>name;
		int  k=name[0]-'A';//将字母转换为数字的形式进行保存; 
		cin>>m[k].a>>m[k].b;
	}
	string expr;//定义字符串进行输入; 
	while(cin>>expr){
		int len=expr.length();//计算长度 
		bool error = false ;//标记 
		int ans = 0;//计算这个乘法的和; 
		for(int i=0;i<len;i++)
		{
			if(isalpha(expr[i])) //这是一个函数,其作用:检测该元素是不是为字母的形式  
			  s.push(m[expr[i]-'A']);//入栈; 
			else if(expr[i]==')'){
				Matrix m2 =s.top(); s.pop();       
				Matrix m1 =s.top(); s.pop();
				if(m1.b!=m2.a)    {    //判断是否可以进行合法的乘法运算   否则就进行标记 
					error = true ;
					break;
				}
				ans+=m1.a*m1.b*m2.b;
				s.push(Matrix(m1.a,m2.b));
			}
		}
		if(error)    printf("error\n");  
		else         printf("%d\n",ans);
	}
	return 0;
}

import cvxpy as cp import numpy as np import pandas as pd data = pd.read_excel('附件1.xlsx') X = data.iloc[1:, 1:2] Y = data.iloc[1:, 2:3] W = data.iloc[2:, 3:4] # 收集点垃圾量(i=1..n) xi = X.values.flatten() # 转换为一维数组 (n,) yi = Y.values.flatten() # 转换为一维数组 (n,) wi = W.values.flatten() # 转换为一维数组 (n,) # 定义参数 n = 30 # 收集点数量(i=1..n,0为处理厂) K = 30 # 车辆总数 Q = 5 # 最大载重 # 计算距离矩阵dij(i,j=0..n) dij = np.zeros((n+1, n+1)) for i in range(n+1): for j in range(n+1): dij[i, j] = np.sqrt((xi[i] - xi[j])**2 + (yi[i] - yi[j])**2) x = cp.Variable((n+1, n+1, K), boolean=True) # x_ijv: 车辆v从i到j y = cp.Variable((n, K), boolean=True) # y_iv: 车辆v服务收集点i(i=1..n,索引0..n-1) z = cp.Variable(K, boolean=True) # z_v: 使用车辆v u = cp.Variable((n+1, K), nonneg=True) # u_iv: 车辆v访问i后的累计载重(i=0..n,u[0,v]=0) objective = cp.Minimize(cp.sum(cp.sum(cp.sum(dij @ x, axis=2), axis=1), axis=0)) # 约束条件 constraints = [] # 1. 每个收集点被 exactly 一辆车服务(i=1..n,对应y的索引0..n-1) for i in range(n): constraints.append(cp.sum(y[i, :]) == 1) # 2. 流量守恒(i=1..n,处理厂i=0的约束在6中) for i in range(1, n+1): # 收集点i(1..n,y索引i-1) for v in range(K): constraints.append(cp.sum(x[i, :, v]) == y[i-1, v]) # 离开i的次数等于服务i的次数 constraints.append(cp.sum(x[:, i, v]) == y[i-1, v]) # 进入i的次数等于服务i的次数 # 3. 载重约束 for v in range(K): constraints.append(cp.sum(wi * y[:, v]) <= Q * z[v]) # 4. MTZ约束(子回路消除) for v in range(K): constraints.append(u[0, v] == 0) # 处理厂出发时载重为0 for i in range(1, n+1): # 收集点i(1..n,wi[i-1]) constraints.append(u[i, v] >= wi[i-1]) # 载重下限 constraints.append(u[i, v] <= Q) # 载重上限 for j in range(1, n+1): if i != j: constraints.append(u[i, v] - u[j, v] + Q * x[i, j, v] <= Q - wi[j-1]) # 5. 车辆使用约束:服务收集点则使用车辆 for i in range(n): for v in range(K): constraints.append(y[i, v] <= z[v]) # 6. 出发返回约束(处理厂i=0,出发到收集点1..n,返回从收集点1..n到0) for v in range(K): constraints.append(cp.sum(x[0, 1:, v]) == z[v]) # 出发次数等于车辆使用 constraints.append(cp.sum(x[1:, 0, v]) == z[v]) # 返回次数等于车辆使用 # 建立问题并求解 problem = cp.Problem(objective, constraints) problem.solve() # 输出结果(示例,需根据实际需求处理) print("最优目标值:", problem.value) print("使用的车辆:", z.value)D:\python\python.exe D:\35433\Documents\数模练习\电工杯\问题1.py D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 1 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 2 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 3 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 4 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 5 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 6 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 7 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 8 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 9 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 10 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 11 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 12 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 13 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 14 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 15 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 16 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 17 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 18 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 19 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 20 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 21 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 22 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 23 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 24 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 25 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 26 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 27 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 28 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 29 times so far. D:\python\Lib\site-packages\cvxpy\expressions\expression.py:674: UserWarning: This use of ``*`` has resulted in matrix multiplication. Using ``*`` for matrix multiplication has been deprecated since CVXPY 1.1. Use ``*`` for matrix-scalar and vector-scalar multiplication. Use ``@`` for matrix-matrix and matrix-vector multiplication. Use ``multiply`` for elementwise multiplication. This code path has been hit 30 times so far. D:\python\Lib\site-packages\cvxpy\reductions\solvers\solving_chain_utils.py:41: UserWarning: The problem has an expression with dimension greater than 2. Defaulting to the SCIPY backend for canonicalization.
最新发布
05-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值