矩阵乘幂

来源:互联网 发布:淘宝中秋节活动logo 编辑:程序博客网 时间:2024/04/27 20:58
问题描述:给定一个 N 阶矩阵 A,输出 A 的 M 次幂(M 是非负整数) ,例如:
A =
1 2
3 4
A 的 2 次幂
7 10
15 22
输入格式:第一行是一个正整数 N、M(1<=N<=30, 0<=M<=5) ,表示矩阵 A 的阶数和要求的幂数
接下来 N 行,每行 N 个绝对值不超过 10 的非负整数,描述矩阵 A 的值
输出格式:输出共 N 行,每行 N 个整数,表示 A 的 M 次幂所对应的矩阵。相邻的数之间用一个空格
隔开
样例输入
2 2
1 2
3 4
样例输出
7 10

15 22


//********************矩阵乘幂 #include <iostream>#include <queue>#include <math.h>#include <string.h>using namespace std;const int Max = 30;int main(){int N,M;cin >> N >> M;int x[N][N],f[N][N],temp[N][N];for(int i=0;i<N;i++)for(int j=0;j<N;j++){if(i==j) temp[i][j]=1;else temp[i][j]=0;}for(int i=0;i<N;i++)for(int j=0;j<N;j++)cin >> x[i][j];if(M>0){for(int count=1;count<=M;count++){for(int i=0;i<N;i++)for(int j=0;j<N;j++){int sum=0;for(int k=0;k<N;k++)sum+=temp[i][k]*x[k][j];f[i][j]=sum;}for(int i=0;i<N;i++){for(int j=0;j<N;j++){if(count<M) temp[i][j]=f[i][j];else cout << f[i][j] << " ";}if(count==M&&i<N-1) cout << endl;}}}elsefor(int i=0;i<N;i++){for(int j=0;j<N;j++)cout << temp[i][j] << " ";if(i<N-1) cout << endl;}return 0;}


0 0
原创粉丝点击