首页 > 代码库 > Power of Matrix 等比数列求和 矩阵版!
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 等比数列求和 矩阵版!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。