矩阵乘法

【链接】nbu1747点击打开链接

【题目】

矩阵乘法

Time Limit:512MS  Memory Limit:65536K

Description

You are given three n × n matrices A, B and C. Does the equation A × B = C hold true?

Input

The first line of input contains a positive integer n (n ≤ 500) followed by the the three matrices A, B and C respectively. Each matrix's description is a block of n × n integers.
It guarantees that the elements of A and B are less than 100 in absolute value and elements of C are less than 10,000,000 in absolute value.

Output

Output "YES" if the equation holds true, otherwise "NO".

Sample Input

2
1 0
2 3
5 1
0 8
5 1
10 26

Sample Output

YES

Hint

Multiple inputs will be tested. So O(n3) algorithm will get TLE.

【算法】

直接按矩阵的乘法来做的话就是O(n^3)了,要超时的。

定义一个1*n的随机矩阵T,则若T*A*B=T*C,那么A*B=C,这样做的时间复杂度就是3*n^2了。

据说这样有一定的出错概率,因为乘法法则是要比较n*n个数相等才能判矩阵相等,现在缩减到了只判断n个数,所以……

但是概率是很小的,可以忽略不计,另外定义两个这样的T,进行两次判断的话,出错概率就更低了。

【代码】

#include<stdio.h>
#include<string.h>
int a[501][501],b[501][501],c[501][501],t1[501],t2[501],t3[501],t;
int main()
{
	int n,i,j,f;
	while(scanf("%d",&n)!=EOF)
	{
		for(i=0;i<n;i++)
			t1[i]=2*i+8;
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				scanf("%d",&a[i][j]);
		}
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				scanf("%d",&b[i][j]);
		}
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				scanf("%d",&c[i][j]);
		}
		memset(t2,0,sizeof(t2));
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				t2[i]+=t1[j]*a[j][i];
		}
		memset(t3,0,sizeof(t3));
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
				t3[i]+=t2[j]*b[j][i];
		}
		f=0;
		for(i=0;i<n;i++)
		{
			t=0;
			for(j=0;j<n;j++)
				t+=t1[j]*c[j][i];
			if(t!=t3[i]) {printf("NO\n");f=1;break;}
		}
		if(f==0) printf("YES\n");
	}
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值