题目1474:矩阵幂

题目描述:

给定一个n*n的矩阵,求该矩阵的k次幂,即P^k。

输入:

输入包含多组测试数据。
数据的第一行为一个整数T(0<T<=10),表示要求矩阵的个数。
接下来有T组测试数据,每组数据格式如下: 
第一行:两个整数n(2<=n<=10)、k(1<=k<=5),两个数字之间用一个空格隔开,含义如上所示。
接下来有n行,每行n个正整数,其中,第i行第j个整数表示矩阵中第i行第j列的矩阵元素Pij且(0<=Pij<=10)。另外,数据保证最后结果不会超过10^8。

输出:

对于每组测试数据,输出其结果。格式为:
n行n列个整数,每行数之间用空格隔开,注意,每行最后一个数后面不应该有多余的空格。

样例输入:
3
2 2
9 8
9 3
3 3
4 8 4
9 3 0
3 5 7
5 2
4 0 3 0 1
0 0 5 8 5
8 9 8 5 3
9 6 1 7 8
7 2 5 7 3
样例输出:
153 96
108 81
1216 1248 708
1089 927 504
1161 1151 739
47 29 41 22 16
147 103 73 116 94
162 108 153 168 126
163 67 112 158 122
152 93 93 111 97



1
#include<iostream> 2 using namespace std; 3 //for i=0 to n-1 4 // for j=0 to n-1 5 // for k 6 //c[i][j]=sum(b[i][0 to n-1]*a[0 to n-1][j]) 7 struct shenme 8 { 9 int m[10][10]; 10 }; 11 struct shenme arry[10]; 12 struct shenme multiply(struct shenme a,struct shenme b, int n) 13 { 14 struct shenme c; 15 for(int i=0;i<n;i++) 16 { 17 for(int j=0;j<n;j++) 18 { 19 c.m[i][j]=0; 20 for(int k=0;k<n;k++) 21 { 22 c.m[i][j]+=a.m[i][k]*b.m[k][j]; 23 24 } 25 26 } 27 28 } 29 return c; 30 31 } 32 void inite(int n,int t) 33 { 34 for(int i=0;i<n;i++) 35 for(int j=0;j<n;j++) 36 { 37 cin>>arry[t].m[i][j]; 38 } 39 } 40 struct shenme jiecheng(int k,int t,int n) 41 { 42 struct shenme temp; 43 for(int i=0;i<n;i++) 44 for(int j=0;j<n;j++) 45 temp.m[i][j]=arry[t].m[i][j]; 46 for(int i=2;i<=k;i++) 47 { 48 temp=multiply(arry[t],temp,n);//传入两个结构体 49 } 50 return temp; 51 } 52 void out(struct shenme result,int n) 53 { 54 for(int i=0;i<n;i++) 55 { 56 for(int j=0;j<n;j++) 57 { 58 if(j!=n-1) 59 cout<<result.m[i][j]<<" "; 60 else 61 cout<<result.m[i][j]; 62 } 63 cout<<endl; 64 } 65 } 66 int main() 67 { 68 int T;//输入几个数组?(结构体) 69 cin>>T; 70 for(int t=0;t<T;t++)//t第几个数组 71 { 72 int n,k; 73 cin>>n>>k; 74 //数组初始化 75 inite(n,t); 76 struct shenme result; 77 result=jiecheng(k,t,n); 78 out(result,n); 79 } 80 return 0; 81 }
原文地址:https://www.cnblogs.com/ldphoebe/p/5604739.html