算法导论 矩阵乘法(简单分治)

#include <stdio.h>
#define LEN 4

typedef struct
{
	int rowstart;
	int rowend;
	int colstart;
	int colend;
}Square;

int A[LEN][LEN]={{1,2,3,4},{3,4,5,6},{5,6,7,8},{7,8,9,10}};
int B[LEN][LEN]={{5,6,7,8},{7,8,9,10},{11,12,13,14},{15,16,17,18}};

void recurMult(int C[LEN][LEN],Square a,Square b)
{
	if(a.rowstart==a.rowend && a.colstart==a.colend &&
		b.rowstart==b.rowend && b.colstart==b.colend)
	{
		C[a.rowstart][b.colstart]+=A[a.rowstart][a.colstart]*B[b.rowstart][b.colstart];
		return;
	}

	Square a11={a.rowstart,(a.rowstart+a.rowend)/2,a.colstart,(a.colstart+a.colend)/2};
	Square a12={a.rowstart,(a.rowstart+a.rowend)/2,(a.colstart+a.colend)/2+1,a.colend};
	Square a21={(a.rowstart+a.rowend)/2+1,a.rowend,a.colstart,(a.colstart+a.colend)/2};
	Square a22={(a.rowstart+a.rowend)/2+1,a.rowend,(a.colstart+a.colend)/2+1,a.colend};
	Square b11={b.rowstart,(b.rowstart+b.rowend)/2,b.colstart,(b.colstart+b.colend)/2};
	Square b12={b.rowstart,(b.rowstart+b.rowend)/2,(b.colstart+b.colend)/2+1,b.colend};
	Square b21={(b.rowstart+b.rowend)/2+1,b.rowend,b.colstart,(b.colstart+b.colend)/2};
	Square b22={(b.rowstart+b.rowend)/2+1,b.rowend,(b.colstart+b.colend)/2+1,b.colend};

	recurMult(C,a11,b11);
	recurMult(C,a12,b21);
	recurMult(C,a11,b12);
	recurMult(C,a12,b22);
	recurMult(C,a21,b11);
	recurMult(C,a22,b21);
	recurMult(C,a21,b12);
	recurMult(C,a22,b22);
}

void print(int a[LEN][LEN])
{
	for(int i=0;i<LEN;i++)
	{
		for(int j=0;j<LEN;j++)
		{
			printf("%4d ",a[i][j]);
		}
		printf("\n");
	}
}

int main()
{
	int C[LEN][LEN]={0};
	Square a={0,LEN-1,0,LEN-1};
	Square b={0,LEN-1,0,LEN-1};
	recurMult(C,a,b);
	print(C);
	getchar();
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值