题目链接
题目描述
给定一个n*n的矩阵,求该矩阵的k次幂,即P^k。
输入描述:
第一行:两个整数n(2<=n<=10)、k(1<=k<=5),两个数字之间用一个空格隔开,含义如上所示。
接下来有n行,每行n个正整数,其中,第i行第j个整数表示矩阵中第i行第j列的矩阵元素Pij且(0<=Pij<=10)。
另外,数据保证最后结果不会超过10^8。
输出描述:
对于每组测试数据,输出其结果。格式为:
n行n列个整数,每行数之间用空格隔开,注意,每行最后一个数后面不应该有多余的空格。
示例1
输入
2 2
9 8
9 3
输出
153 96
108 81
题解:
自定义函数算出二次方的矩阵,再多次使用函数求k次方。
#include <iostream>
using namespace std;
int buf[10][10];
void getmux(int buf[10][10], int ans[10][10], int n){
int ans2[10][10];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
ans2[i][j] = 0;
}
}
for(int x = 0; x < n; x++){
for(int y = 0; y < n; y++){
for(int i = 0; i < n; i++){
ans2[x][y] += ans[x][i] * buf[i][y];
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
ans[i][j] = ans2[i][j];
}
}
}
int main(){
int n;
while(cin >> n){
int k;
int ans[10][10];
cin >> k;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> buf[i][j];
ans[i][j] = buf[i][j];
}
}
while(--k > 0){
getmux(buf, ans, n);
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n-1; j++){
cout << ans[i][j] << ' ';
}
cout << ans[i][n-1] << endl;
}
}
return 0;
}