H. Matrix Multiplication
Description
Johnny and John are good friends. Johnnyis going to take the entrance exams for postgraduate schools. Recently,he is reviewing Linear Algebra. Johnny always says that he isvery skillful at matrix multiplication. As we all know that, if we know matrixa (m rows and n columns) and b (n rows and t columns), the result matrix c (mrows and t columns) can be calculated by expression c (i, j)=(1<= i <= m, 1 <= j <= t). But John wantsto make things difficult. He wants Johnny to calculate matrix cusing expression c (i, j) = (1<= i <= m,1 <= j <= t, i + k is odd and k + j is even). We consider that 2 is oddand even. At the beginning, c (i, j) =0.
Input
The first line ofinput is the number T of test case.
The first line ofeach test case contains three integers, m, n, t, indicates the size of thematrix a and b. We always assume that the rows of matrix a equals to matrix b'scolumns.
The next m linesdescribe the matrix a. Each line contains n integers.
Then n linesfollowed, each line contains t integers, describe the matrix b.
1<=T <= 10, 1 <= m, n, t <= 100, 0 <= a (i, j) <= 100, 0 <= b(i, j) <= 100.
Output
For each test caseoutput the matrix c. The numbers are separated by spaces. There is no space at the end of each line.
Sample Input
1
2 2 2
1 2
2 3
2 3
3 0
Sample Output
2 0
4 0
这个题解题的关键是对符合条件的k值的判断,题目中定义了2既是偶数又是奇数,然后是当i + k 为奇数且k + j为偶数时才进行这个乘法,根据题意可以写出判断条件((i+k==2||(i+k)%2!=0)&&(j+k)%2==0),然后就是直接算了。题目有多组测试数据,所以这里一定要对c数组进行清零memset(c,0,sizeof(c))。
题目中提到了,输出中每一行的末尾没有空格。所以在输出的时候要注意一下空格的输出,简单的用一个if解决。
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
long long a[111][111],b[111][111];
long long c[111][111];
int main()
{
int T;
int m,n,t,k;
int i,j;
cin>>T;
while(T--)
{
memset(c,0,sizeof(c));
cin>>m>>n>>t;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
cin>>a[i][j];
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=t;j++)
{
cin>>b[i][j];
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=t;j++)
{
for(k=1;k<=n;k++)
{
if((i+k==2||(i+k)%2!=0)&&(j+k)%2==0)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=t;j++)
{
cout<<c[i][j];
if(j!=t)
cout<<" ";
else
cout<<endl;
}
}
}
return 0;
}