您的位置:首页 > 其它

hdu 4920 Matrix multiplication (矩阵乘法)

2015-08-17 22:41 429 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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 Aij. The next n lines describe the matrix B in similar format (0≤Aij,Bij≤109).

[align=left]Output[/align]
For each tests:
Print n lines. Each of them contain n integers -- the matrix A×B in similar format.

[align=left]Sample Input[/align]

1
0

1
2

0 1
2 3
4 5
6 7

[align=left]Sample Output[/align]

0
0 1
2 1

矩阵乘法就三个for循环而已,没什么说的。不过此题好坑,要小心,如何坑的,请看代码。

#include<cstdio>
#include<cstring>
using namespace std;
int n,a[804][804],b[804][804],c[804][804];
int main()
{
int i,j,k;
while (~scanf("%d",&n))
{
for (i=1;i<=n;i++)
for (j=1;j<=n;j++) c[i][j]=0;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
a[i][j]%=3;//每输入都要%3,让数据变小,下面才可不%3。
}
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&b[i][j]);
b[i][j]%=3;
}
for (k=1;k<=n;k++) //这个循环不能换在j循环下面,不然会超时。什么原因暂时不清楚。
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
c[i][j]+=a[i][k]*b[k][j]; //这里不能%3,不然会超时,因为多算了一步。
for (i=1;i<=n;i++)
{
for (j=1;j<n;j++)
printf("%d ",c[i][j]%3);
printf("%d\n",c[i][j]%3);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: