BUPT-矩阵幂

题目链接

https://www.nowcoder.com/practice/31e539ab08f949a8bece2a7503e9319a?tpId=67&tqId=29638&tPage=1&ru=/kaoyan/retest/1005&qru=/ta/bupt-kaoyan/question-ranking

题目描述

给定一个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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值