计算矩阵运算的乘法次数

//描述:
//矩阵乘法的运算量与矩阵乘法的顺序强相关。
//
//例如:
//A是一个50×10的矩阵,B是10×20的矩阵,C是20×5的矩阵
// 
//计算A*B*C有两种顺序:((AB)C)或者(A(BC)),前者需要计算15000次乘法,后者只需要3500次。
// 
//编写程序计算不同的计算顺序需要进行的乘法次数
  
//知识点: 字符串 
//题目来源: 内部整理 
//练习阶段: 中级 
//运行时间限制: 10Sec
//内存限制: 128MByte
//输入:  
//输入多行,先输入要计算乘法的矩阵个数n,每个矩阵的行数,列数,总共2n的数,最后输入要计算的法则
//3       //矩阵个数n 
//50 10   //矩阵A的行数50,列数10
//10 20   //矩阵B的行数10,列数20
//20 5    //矩阵C的行数20,列数5
//(A(BC)) //矩阵从A开始命名,A、B、C、D...以此类推,通过括号表示运算顺序
// 
//输出:  
//输出需要进行的乘法次数
// 
//样例输入:
//3
//50 10
//10 20
//20 5

//(A(BC))

//样例输出:

//3500

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cishu=0;

struct juzhen_info{
	int row;
	int column;
};
static int index=0;
struct juzhen_info chengfa_cishu(int n, struct juzhen_info *juzhen, char* exep){
	int flag=0;
	struct juzhen_info cur_juzhen;
	struct juzhen_info temp;
	while(*(exep+index)!='\0'){
		if(*(exep+index)=='('){
			index++;
			if(flag==0){
				//保存cur_juzhen
				cur_juzhen = chengfa_cishu(n, juzhen, exep);
				flag = 1;
			}
			else{
				//计算次数
				temp = chengfa_cishu(n, juzhen, exep);
				cishu += cur_juzhen.row * cur_juzhen.column * temp.column;
				cur_juzhen.column = temp.column;
			}
			//chengfa_cishu(n, juzhen, exep);
		}
		else if(*(exep+index)==')'){
			index++;
			return cur_juzhen;
		}
		else if(*(exep+index)>64&&*(exep+index)<65+n){
			if(flag==0){
				cur_juzhen.row = juzhen[*(exep+index)-65].row;
				cur_juzhen.column = juzhen[*(exep+index)-65].column;
				flag = 1;
				index++;
			}
			else{
				cishu += cur_juzhen.row * cur_juzhen.column * juzhen[*(exep+index)-65].column;
				cur_juzhen.column = juzhen[*(exep+index)-65].column;
				index++;
			}
		}
	}
}

int main(void){
	int n;
	int k;
	char exep[100]; char *ptr;

	struct juzhen_info *juzhen, *juzhen_temp;

	scanf("%d", &n);
	juzhen_temp = juzhen = (struct juzhen_info*)malloc(n*sizeof(struct juzhen_info));
	
	for(k=0; k<n; k++){
		scanf("%d %d", &juzhen->row, &juzhen->column);
		juzhen++;
	}

	scanf("%s", exep);
	ptr = strupr(exep);

	chengfa_cishu(n, juzhen_temp, ptr);
	printf("%d",cishu);

	system("pause");
	return 0;
}

转载于:https://www.cnblogs.com/xhyzjiji/p/6159396.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值