【poj3233】Matrix Power Series 矩阵+快速幂
2016-01-11 20:42
375 查看
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题意:给你一个n*n的矩阵A,求
∑k=1nAk
其中每个元素mod m。
二分,可以像快速幂一样递归处理。
先把A想象成数字,则:
A1+A2+A3+A4+A5+A6
=(A1+A2+A3)+A3∗(A1+A2+A3)
=(1+A3)∗(A1+A2+A3)
对于矩阵,重载了+和*,1为单位矩阵,就一样做了。
代码(不知道为何,很慢):
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int n,mod; struct matrix{ int num[32][32]; void init() { memset(num,0,sizeof(num)); for(int i = 1;i <= n;i ++) num[i][i] = 1; } }; matrix operator *(const matrix &a,const matrix &b) { matrix ans; for(int i = 1;i <= n;i ++) { for(int j = 1;j <= n;j ++) { ans.num[i][j] = 0; for(int k = 1;k <= n;k ++) { ans.num[i][j] += a.num[i][k] * b.num[k][j]; ans.num[i][j] %= mod; } } } return ans; } matrix operator +(const matrix &a,const matrix &b) { matrix ans; for(int i = 1;i <= n;i ++) { for(int j = 1;j <= n;j ++) { ans.num[i][j] = (a.num[i][j] + b.num[i][j]) % mod; } } return ans; } matrix ksm(matrix a,int b) { matrix ans; ans.init(); while(b) { if(b & 1) ans = ans * a; a = a * a; b >>= 1; } return ans; } void print(const matrix &ans) { for(int i = 1;i <= n;i ++) { for(int j = 1;j <= n;j ++) { printf("%d ",ans.num[i][j]); } puts(""); } } matrix ask(const matrix &a,int b) { if(b == 1) return a; matrix ans; ans.init(); ans = (ans + ksm(a,b >> 1)) * ask(a,b >> 1); // print(ans); if(b & 1) return ans + ksm(a,b); else return ans; } int main() { matrix ans; int k; while(~scanf("%d%d%d",&n,&k,&mod)) { for(int i = 1;i <= n;i ++) { for(int j = 1;j <= n;j ++) { scanf("%d",&ans.num[i][j]); } } ans = ask(ans,k); print(ans); } return 0; }
相关文章推荐
- 【剑指offer】4.3举例让抽象问题具体化——面试题24:二叉搜索树的后序遍历序列
- SGI Allocator内存管理(一)
- HDU 1494 跑跑卡丁车 (分段DP)
- 训练指南(白书)第二章:数学基础
- python 列表和元组
- POJ_P1274 The Perfect Stall(二分图匹配+匈牙利算法)
- CocoaPods 的个人使用总结
- Git版本恢复命令reset
- 序列化机制
- 【剑指offer】4.3举例让抽象问题具体化——面试题23:从上往下打印二叉树
- 【银行家算法】操作系统课程设计
- 【jsp】The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path
- ContentProvider实现两个程序间共享数据
- 创建数据库普通临时表和创建数据库全局变量表和俩者的区别
- 《从零开始自学iOS》_02
- Android studio 开发环境搭建
- Android四大组件---Activity之启动模式及启动模式的应用场景
- 正则表达式
- ORACLE伪列探究
- 【剑指offer】4.3举例让抽象问题具体化——面试题22:栈的压入、弹出序列