Matrix Multiplication
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
for(int k=0;k<n;++k){
c[i][j]+=a[i][k]*b[k][j];
}
}
}
example
Basic training matrix multiplication
time limit: 1.0s memory limit: 512.0MB
problem description
given a rank N matrix A, M A is the output power (M is a non-negative integer)
, for example:
A =
. 1 2
. 3. 4
2 A power of
7 10
15 22 is
the input format
of the first row is a positive integer N, M (1 <= N <= 30, 0 <= M <= 5), and represents a power of the order of the matrix a requires
the following N rows, each line N absolute values non-negative integer not exceeding 10, the value of matrix a described
output format
output common N lines of N integers, M represents the power of the matrix a corresponding to the. Separated by a space between adjacent ones of the number of
sample input
2 2
. 1 2
. 3. 4
sample output
. 7 10
15 22 is
Precautions: zero power matrix is the identity matrix
#include<iostream>
#include<cstring>
using namespace std;
const int N = 33;
int a[N][N],b[N][N],c[N][N];
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cin>>a[i][j];
c[i][j]=b[i][j]=a[i][j];
}
}
if(m==0){
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
if(i==j)c[i][j]=1;
else c[i][j]=0;
}
}
}
else{
m--;
while(m--){
memcpy(b,c,sizeof c);
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
c[i][j]=0;
for(int k=0;k<n;++k){
c[i][j]+=a[i][k]*b[k][j];
}
}
}
}
}
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}