您的位置:首页 > 其它

计算矩阵运算的乘法次数

2014-05-21 14:12 302 查看
//描述:

//矩阵乘法的运算量与矩阵乘法的顺序强相关。

//

//例如:

//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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: