6.5 矩阵
矩阵加法与乘法
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN=100;
struct Matrix{
int row,col;
int matrix[MAXN][MAXN];
Matrix(){} //构造函数
Matrix(int r,int c):row(r),col(c){}
};
Matrix Add(Matrix x,Matrix y){
Matrix answer=Matrix(x.row,x.col);
for(int i=0;i<answer.row;++i){
for(int j=0;j<answer.col;++j){
answer.matrix[i][j]=x.matrix[i][j]+y.matrix[i][j];
}
}
return answer;
}
Matrix Multiply(Matrix x,Matrix y){
Matrix answer=Matrix(x.row,y.col);
for(int i=0;i<answer.row;i++){
for(int j=0;j<answer.col;++j){
answer.matrix[i][j]=0;
for(int k=0;k<x.col;++k){
answer.matrix[i][j]+=x.matrix[i][k]*y.matrix[k][j];
}
}
}
return answer;
}
void InputMatrix(Matrix &x){
for(int i=0;i<x.row;++i){
for(int j=0;j<x.col;++j){
scanf("%d",&x.matrix[i][j]);
}
}
return;
}
void OutputMatrix(Matrix x){
for(int i=0;i<x.row;++i){
for(int j=0;j<x.col;++j){
printf("%d ",x.matrix[i][j]);
}
printf("\n");
}
return;
}
int main(){
Matrix x(2,3);
Matrix y(3,2);
InputMatrix(x);
InputMatrix(y);
Matrix answer=Multiply(x,y);
OutputMatrix(answer);
return 0;
}
矩阵转置:原来的行变为现在的列,原来的列变为现在的行
矩阵幂
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN=100;
struct Matrix{
int row,col;
int matrix[MAXN][MAXN];
Matrix(){} //构造函数
Matrix(int r,int c):row(r),col(c){}
};
//矩阵加法
Matrix Add(Matrix x,Matrix y){
Matrix answer=Matrix(x.row,x.col);//矩阵的初始化
for(int i=0;i<answer.row;++i){
for(int j=0;j<answer.col;++j){
answer.matrix[i][j]=x.matrix[i][j]+y.matrix[i][j];
}
}
return answer;
}
//矩阵乘法
Matrix Multiply(Matrix x,Matrix y){
Matrix answer=Matrix(x.row,y.col);
for(int i=0;i<answer.row;i++){
for(int j=0;j<answer.col;++j){
answer.matrix[i][j]=0;
for(int k=0;k<x.col;++k){
answer.matrix[i][j]+=x.matrix[i][k]*y.matrix[k][j];
}
}
}
return answer;
}
//矩阵转置
Matrix Transpose(Matrix x){
Matrix answer=Matrix(x.col,x.row);
for(int i=0;i<x.row;++i){
for(int j=0;j<x.col;++j){
answer.matrix[i][j]=x.matrix[j][i];
}
}
return answer;
}
//矩阵求幂(求k次幂)必须保证行和列相等才能求幂
Matrix QuickPower(Matrix x,int n){
Matrix answer=Matrix(x.row,x.col);
for(int i=0;i<answer.row;++i){
for(int j=0;j<answer.col;++j){
if(i==j){
answer.matrix[i][j]=1;
}else{
answer.matrix[i][j]=0;
}
}
}
while(n!=0){ //快速幂的方法,将n转化为2进制
if(n%2==1){
answer=Multiply(answer,x); //矩阵相乘
}
n/=2;
x=Multiply(x,x);
}
return answer;
}
//输入矩阵
void InputMatrix(Matrix &x){
for(int i=0;i<x.row;++i){
for(int j=0;j<x.col;++j){
scanf("%d",&x.matrix[i][j]);
}
}
return;
}
//输出矩阵
void OutputMatrix(Matrix x){
for(int i=0;i<x.row;++i){
for(int j=0;j<x.col;++j){ //每行数之间用空格隔开,每行最后一个数后面不应该有多余的空格
if(j==0){
printf("%d",x.matrix[i][j]);
} else{
printf(" %d ",x.matrix[i][j]);
}
}
printf("\n");
}
return;
}
int main(){
int n,k;
while(scanf("%d%d",&n,&k)!=EOF){
Matrix x=Matrix(n,n);
InputMatrix(x);
Matrix answer=QuickPower(x,k);
OutputMatrix(answer);
}
return 0;
}