题目描述
这是一道模板题。
分别给定 n×p 和 p×m 的两个矩阵 A 和 B,求 A×B。
输入格式
第一行三个正整数 n、p、m,表示矩阵的长宽。
之后的 n 行,每行 p 个整数,表示矩阵 A。
之后的 p 行,每行 m 个整数,表示矩阵 B。
输出格式
输出 n 行,每行 m 个整数,表示矩阵 A×B,每个数模 10 ^ 9 + 7 输出。
样例
输入数据 1
3 4 5
-2 -8 -9 8
-10 0 6 -8
-10 -6 6 9
4 -7 5 -5 9
10 -2 -10 5 5
-3 -7 -3 8 -2
-6 7 7 3 -2
Copy
输出数据 1
999999898 149 153 999999929 999999951
999999997 999999979 999999883 74 999999921
999999835 103 55 95 999999857
Copy
数据范围与提示
1 <n, p, m ≤ 500,−10^9≤Ai,j,Bi,j≤10*9
反思总结:
1、熟悉矩阵乘法,推导公式耗时太长
行乘列:a [ i ] [ k ] * b [ k ] [ j ]
2、数据范围的判断很重要:这道题要开long long , int 直接溢出!
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <vector>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
const int x=1000000000+7;
int n,p,m;
int a[505][505],b[505][505];
int main() {
scanf("%d%d%d",&n,&p,&m);
for(int i=0; i<n; i++) {
for(int j=0; j<p; j++)
scanf("%d",&a[i][j]);
}
for(int i=0; i<p; i++) {
for(int j=0; j<m; j++)
scanf("%d",&b[i][j]);
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
long long temp=0;
for(int k=0; k<p; k++) {
temp=(temp%x+((long long )a[i][k]*b[k][j])%x)%x;
}
if(temp<0)
temp+=x;
printf("%d ",temp);
}
printf("\n");
}
return 0;
}