矩阵快速幂

该代码示例展示了如何使用C++编程实现矩阵快速幂算法,用于高效地进行矩阵乘法。程序首先定义了一个Matrix结构体,包含了矩阵乘法、初始化、输入和输出等方法,然后在主函数中读取矩阵并进行快速幂运算,最后输出结果。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;

inline int read(int& x) {
	char ch = getchar();
	int f = 1; x = 0;
	while (ch > '9' || ch < '0') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); }
	return x * f;
}

const int MOD = 1e9 + 7;
long long int n,m;

struct Matrix {
	int a[202][202];
	Matrix() { memset(a, 0, sizeof(a)); }

	void Init() {
		for (int i = 0; i < n; i++)a[i][i] = 1;
	}

	Matrix operator*(const Matrix& input)const {
		Matrix ret;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int k = 0; k < n; k++) {
					ret.a[i][j] = (ret.a[i][j] + (long long int)a[i][k] * input.a[k][j]) % MOD;
				}
			}
		}
		return ret;
	}
	void Input() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				cin >> a[i][j];
			}
		}
	}
	void OutPut() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				cout << a[i][j] << " ";
			}
			cout << endl;
		}
	}
}A, res;

void quickPow(long long int k) {
	res.Init();
	while (k) {
		if (k & 1) res = res * A;
		A = A * A;
		k >>= 1;
	}
	res.OutPut();
}

int main()
{
	cin >> n >> m;
	A.Input();
	quickPow(m);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值