Power of Matrix 等比數列求和 矩陣版!
阿新 • • 發佈:2017-07-29
stack 求和 nbsp mem ring return fin mes double
#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; typedeflong 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 (inti = 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 等比數列求和 矩陣版!