題目描述
給你一個n*n的矩陣,
求其矩陣的k次冪,即Pk
輸入格式
第一行,一個整數T(0
//#include <iostream>
#include <cstdio>
#define MAZSIZE_MATRIX 100
using namespace std;
struct Matrix{
int data[MAZSIZE_MATRIX][MAZSIZE_MATRIX];
int row,column;
Matrix(int row=0,int column=0){
this->row=row;
this->column=column;
}
void zeroMatrix(){//init all elem ->0
for (int i=0;i<row;i++)
for (int j=0;j<column;j++)
data[i][j]=0;
}
Matrix operator+(const Matrix matr)const{//this+matr,1.same rowNum,same columnNum;2.return the result matrix¡ª¡ªtemp
Matrix temp(row,column);
temp.zeroMatrix();
for (int i=0;i<row;i++){
for (int j=0;j<column;j++){
temp.data[i][j]+=data[i][j]+matr.data[i][j];
}
}
return temp;
}
Matrix operator*(const Matrix matr)const{//this*matr,1.mxn,nxs;2.return the result matrix¡ª¡ª,temp;
Matrix temp(row,matr.column);
temp.zeroMatrix();
for (int i=0;i<row;i++){//ÇóµÄÐÐÊý
for (int j=0;j<matr.column;j++){//ÇóµÄÁÐÊý
for (int p=0;p<column;p++){//pΪ×߶¯µÄÓαê
temp.data[i][j]+=(data[i][p])*(matr.data[p][j]);
}
}
}
return temp;
}
Matrix pow(int k){//matr^k ¾ØÕó¿ìËÙÃÝ
//row must ==colum
Matrix pro(row,row),weight(row,row);
//initiate
for (int i=0;i<row;i++){//init pro
for (int j=0;j<row;j++){
if (i==j)
pro.data[i][j]=1;
else
pro.data[i][j]=0;
}
}
for (int i=0;i<row;i++){//init weight
for (int j=0;j<row;j++){
weight.data[i][j]=data[i][j];
}
}
//calculate ¶þ·ÖÇóÃÝ
while (k>0){
if (k%2==1){
//pro*=weight;
pro=pro*weight;
}
//k/=2,weight*=weight;
k/=2;
weight=weight*weight;
}//while
return pro;
}
void print(){
bool firstCase;
for (int i=0;i<row;i++){
firstCase=true;
for (int j=0;j<column;j++){
if (firstCase)
firstCase=false;
else
// cout<<' ';
printf(" ");
// cout<<data[i][j];
printf("%d",data[i][j]);
}
// cout<<endl;
printf("\n");
}
}
};
int main(){
int t,n,k;
scanf("%d",&t);
Matrix matr,ans;
while (t--){
//initiate
//input
scanf("%d%d",&n,&k);
matr.column=matr.row=ans.column=ans.row=n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
scanf("%d",&matr.data[i][j]);
}
}
//cal
ans=matr.pow(k);
//output
ans.print();
}
return true;
}