poj 3233 矩阵高速幂
poj 3233 矩阵快速幂
Matrix Power Series
Description Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak. Input The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order. Output Output the elements of S modulo m in the same way as A is given. Sample Input 2 2 4 0 1 1 1 Sample Output 1 2 2 3 Source
POJ Monthly--2007.06.03, Huang, Jinsong
|
#include <cstdio> #include <iostream> #include <cstring> using namespace std; #define LL long long #define N 60 + 5 int n, k, mod; struct Matrix { LL m[N][N]; Matrix() { memset(m, 0, sizeof m); } }; Matrix Mul(Matrix a, Matrix b) { int t = 2 * n; Matrix tmp; for(int k = 1; k <= t; k++) for(int i = 1; i <= t; i++) for(int j = 1; j <= t; j++) tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k]*b.m[k][j]) % mod; return tmp; } Matrix mul_pow(Matrix a, int k) { Matrix res; for(int i = 1; i <= 2 * n; i++) res.m[i][i] = 1; while(k) { if(k & 1) res = Mul(res, a); a = Mul(a, a); k >>= 1; } return res; } int main() { while(~scanf("%d%d%d", &n, &k, &mod)) { Matrix M; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { scanf("%lld", &M.m[i][j]); } M.m[i+n][i] = M.m[i+n][i+n] = 1; } M = mul_pow(M, k + 1); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { LL a = M.m[i+n][j]; if(i == j) a = (a + mod - 1) % mod; j == n ? printf("%lld\n", a) : printf("%lld ", a); } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。