Power of Matrix 等比数列求和 矩阵版!
Posted joeylee97
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Power of Matrix 等比数列求和 矩阵版!相关的知识,希望对你有一定的参考价值。
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<queue> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 49 #define MOD 10000007 #define INF 1000000009 const double eps = 1e-9; //矩阵快速幂 int n, k; struct Mat { int a[MAXN][MAXN]; Mat() { memset(a, 0, sizeof(a)); } Mat operator *(const Mat& rhs) { Mat ret; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (a[i][j]) { for (int t = 0; t < n; t++) { ret.a[i][t] = (ret.a[i][t] + a[i][j] * rhs.a[j][t])%10; } } } } return ret; } Mat operator +(const Mat& rhs) { Mat ret; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ret.a[i][j] += (a[i][j] + rhs.a[i][j])%10; } } return ret; } }; Mat e; Mat fpow(const Mat& m, int b) { Mat ans, tmp = m; for (int i = 0; i < n; i++) ans.a[i][i] = 1; while (b != 0) { if (b & 1) ans = tmp*ans; tmp = tmp * tmp; b >>= 1; } return ans; } Mat sum(const Mat& m, int k) { if (k == 1) return m; else if (k % 2 == 0) { return (e + fpow(m, k / 2)) * sum(m, k / 2); } else if (k % 2 == 1) { Mat tmp = fpow(m, k / 2 + 1); return (e + tmp)*sum(m, k / 2) + tmp; } } int main() { while (scanf("%d%d", &n,&k), n) { for (int i = 0; i < n; i++) e.a[i][i] = 1; Mat M; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%d", &M.a[i][j]); M.a[i][j] %= 10; } } M = sum(M, k); for (int i = 0; i < n; i++) { printf("%d", M.a[i][0]); for (int j = 1; j < n; j++) { printf("% d", M.a[i][j]); } printf("\n"); } printf("\n"); } }
以上是关于Power of Matrix 等比数列求和 矩阵版!的主要内容,如果未能解决你的问题,请参考以下文章
E - Matrix Power Series (矩阵数列)