【链接】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;
}