题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
do_work(Matrix1,Matrix2,Matrix1.size(),Matrix1[0].size(),Matrix2[0].size());
//注意,m,n,k已经变了,不能把m,n,k传进去
#include <iostream> #include <bits/stdc++.h> #include <vector> using namespace std; void do_work(vector<vector<int>>&Matrix1,vector<vector<int>>&Matrix2,int m,int n,int k); int mul(vector<vector<int>>&Matrix1,int hang,vector<vector<int>>&Matrix2,int lie,int m,int n); int main() { int m,n,k; while(cin>>m>>n>>k){ vector<vector<int>> Matrix1(m,vector<int>(n)); vector<vector<int>> Matrix2(n,vector<int>(k)); int number; int hangindex = 0; while(m--){ int j = n; int lieindex = 0; while(j--){ cin>>number; Matrix1[hangindex][lieindex]=number; lieindex++; } hangindex++; } hangindex = 0; while(n--){ int j = k; int lieindex = 0; while(j--){ cin>>number; Matrix2[hangindex][lieindex]=number; lieindex++; } hangindex++; } //准备好了两个矩阵,对他们进行运算 do_work(Matrix1,Matrix2,Matrix1.size(),Matrix1[0].size(),Matrix2[0].size()); //注意,m,n,k已经变了,不能把m,n,k传进去 } } void do_work(vector<vector<int>>&Matrix1,vector<vector<int>>&Matrix2,int m,int n,int k){ vector<vector<int>>result(m,vector<int>(k)); //vector<vector<int>>result(Matrix1.size(),vector<int>(Matrix2[0].size())); for(int i = 0;i<m;i++){ for(int j = 0;j<k;j++){ result[i][j] = mul(Matrix1,i,Matrix2,j,m,n); } } for(int i = 0;i<m;i++){ for(int j = 0;j<k;j++){ cout<<result[i][j]<<" "; } cout<<endl; } } int mul(vector<vector<int>>&Matrix1,int hang,vector<vector<int>>&Matrix2,int lie,int m,int n){ int result = 0; for(int i = 0;i<n;i++){ result += Matrix1[hang][i]*Matrix2[i][lie]; } return result; } // 64 位输出请用 printf("%lld")