Matrix multiplication
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1839 Accepted Submission(s): 818
Problem Description
Given two matrices A and B of size n×n, find the product of them.
bobo hates big integers. So you are only asked to find the result modulo 3.
bobo hates big integers. So you are only asked to find the result modulo 3.
Input
The input consists of several tests. For each tests:
The first line contains n (1≤n≤800). Each of the following n lines contain n integers -- the description of the matrix A. The j-th integer in the i-th line equals A ij. The next n lines describe the matrix B in similar format (0≤A ij,B ij≤10 9).
The first line contains n (1≤n≤800). Each of the following n lines contain n integers -- the description of the matrix A. The j-th integer in the i-th line equals A ij. The next n lines describe the matrix B in similar format (0≤A ij,B ij≤10 9).
Output
For each tests:
Print n lines. Each of them contain n integers -- the matrix A×B in similar format.
Print n lines. Each of them contain n integers -- the matrix A×B in similar format.
Sample Input
1 0 1 2 0 1 2 3 4 5 6 7
Sample Output
0 0 1 2 1
题意:两个n*n的矩阵相乘。
直接相乘将第二个矩阵进行倒置。b[i][j]<->b[j][i]。另一种方法是将a的一个数进行判断,如果等于0则不进行运算,否则则进行运算。还有,奇怪的是用G++超时,C++和C都AC。至今不懂为什么会这样。
矩阵相乘优化策略:
矩阵转置:矩阵相乘是矩阵A的一行数据元素与矩阵B的一列的数据元素对应相乘,然后再对其积求和,由于C与C++的二维数组是以行为主序存储的,因此矩阵A的行数据元素是连续存储的,而矩阵B的列数据元素是不连续存储的(N*1的矩阵除外),为了在矩阵相乘时对矩阵B也连续读取数据,根据局部性原理对矩阵B进行转置,矩阵转置是数据元素B[i][j]与B[j][i]进行交换,矩阵转置后,矩阵相乘是矩阵A的一行数据元素与转置后的矩阵B的一行的数据元素对应相乘,然后再对其积求和,这个和就是矩阵C的一个数据元素。
#include <stdio.h>
#define LL __int64
int a[900][900],b[900][900],c[900][900];
int main()
{
int n,i,j,k;
while (~scanf("%d",&n))
{
int x;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
{
scanf("%d",&x);
a[i][j]=x%3;
}
for (i=0;i<n;i++)
for (j=0;j<n;j++)
{
scanf("%d",&x);
b[j][i]=x%3;
}
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
c[i][j]=0;
for (k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[j][k];
printf(j==0?"%d":" %d",c[i][j]%3);
}
printf("\n");
}
}
return 0;
}
#include <stdio.h>
#define LL __int64
int a[810][810],b[810][810],c[810][810],n,i,j,k,x;
int main()
{
while (~scanf("%d",&n))
{
for (i=0;i<n;i++)
for (j=0;j<n;j++)
{
scanf("%d",&x);
a[i][j]=x % 3;
}
for (i=0;i<n;i++)
for (j=0;j<n;j++)
{
scanf("%d",&x);
b[j][i]=x % 3;
}
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
c[i][j]=0;
for (k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[j][k];
printf(j==0?"%d":" %d",c[i][j]%3);
}
printf("\n");
}
}
return 0;
}