Matrix Power Series
2016-06-27 16:41
393 查看
Description
Time Limit: 3000MS Memory Limit: 131072KGiven 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 40 1
1 1
Sample Output
1 22 3
Solution & Code
法一:k的范围是109,考虑分治。Si=A+A2+...+Ai
S2i=Ai+1+Ai+2+...+A2i
S2i=Si∗Ai
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; const int maxr = 35; int n, k; ll m; struct matrix{ll val[maxr][maxr];}; matrix U, V, Z, I; matrix multiply(matrix A, matrix B){ matrix C = Z; for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) for(int k = 1; k <= n; ++k){ C.val[i][j] += A.val[i][k] * B.val[k][j]; C.val[i][j] %= m; } return C; } matrix add(matrix A, matrix B){ matrix C = Z; for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j){ C.val[i][j] = A.val[i][j] + B.val[i][j]; C.val[i][j] %= m; } return C; } matrix powmod(matrix A, int x){ matrix B = I; while(x){ if(x & 1) B = multiply(B, A); x = x >> 1; A = multiply(A, A); } return B; } matrix calc(int x){ if(x == 1) return U; int y = x >> 1; matrix L = calc(y); matrix R = multiply(L, powmod(U, y)); if(y * 2 != x) return add(add(L, R), powmod(U, x)); else return add(L, R); } int main(){ cin >> n >> k >> m; for(int i = 1; i <= n; ++i){ for(int j = 1; j <= n; ++j) cin >> U.val[i][j]; I.val[i][i] = 1; } V = calc(k); for(int i = 1; i <= n; ++i){ for(int j = 1; j <= n; ++j) printf("%lld ", V.val[i][j]); puts(""); } return 0; }
法二:如果求s=a+a2+...ak我们可以考虑用矩阵快速幂对其进行加速,求S=A+A2+A3+…+Ak时则可以构造一个元素为矩阵的矩阵,然后用矩阵快速幂加速。
相关文章推荐
- C中实现矩阵乘法的一种高效的方法
- java 二维数组矩阵乘法的实现方法
- strassen矩阵乘法
- 基于内积法的Hadoop的MapReducer框架实现稀疏矩阵乘法(java)
- 对分治算法的几点思考
- 关于“2”这个数字
- hdu 1007 -- Quoit Design
- [Leetcode题解]004 Median of Two Sorted Arrays
- 分治法求最大连续和
- Codeforces Round #299
- poj2299 分治
- [BZOJ1492][NOI2007][斜率优化][动态凸包][DP][分治]货币兑换cash
- mergeSort
- [DP]CH Round#30 T2摆花
- HDU5269 ZYB loves Xor I(分治?解法)
- 算法时间复杂度----分治与递归
- 棋盘覆盖问题
- 矩阵快速幂求斐波那契通项(矩阵乘法优化线性递推式)
- Strassen Algorithm解析
- 分治法--归并排序