矩阵算法模板
来源:互联网 发布:小型图书馆源码 编辑:程序博客网 时间:2024/03/29 05:23
poj 3233
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 40 11 1
Sample Output
1 22 3
#include <cstdio>#include <iostream>#include <cstring>using namespace std;const int NN=32;typedef struct node{ int matrix[NN][NN];}Matrix;Matrix a,sa,unit;int n,m,k;Matrix mtAdd(Matrix a,Matrix b) //矩阵加法(%m){ Matrix c; for (int i=0; i<n; i++) for (int j=0; j<n; j++) { c.matrix[i][j]=a.matrix[i][j]+b.matrix[i][j]; c.matrix[i][j]%=m; } return c;}Matrix mtMul(Matrix a,Matrix b) //矩阵乘法(%m){ Matrix c; for (int i=0; i<n; i++) for (int j=0; j<n; j++) { c.matrix[i][j]=0; for (k=0; k<n; k++) c.matrix[i][j]+=a.matrix[i][k]*b.matrix[k][j]; c.matrix[i][j]%=m; } return c;}Matrix mtPow(Matrix p,int exp) //矩阵快速幂{ Matrix q; q=unit; while (exp!=1) { if (exp&1) { exp--; q=mtMul(p,q); } else { exp>>=1; p=mtMul(p,p); } } return mtMul(p,q);}Matrix MatrixSum(int k){ if (k==1) return a; Matrix tmp,tnow; tmp=MatrixSum(k/2); if (k&1) //k为奇数时sum(k)=(1+A^(k/2+1))*sum(k/2)+A^(k/2+1); { tnow=mtPow(a, k/2+1); tmp=mtAdd(tmp,mtMul(tmp,tnow)); tmp=mtAdd(tnow,tmp); } else //k为偶数时sum(k)=(1+A^(k/2))*sum(k/2) { tnow=mtPow(a, k/2); tmp=mtAdd(tmp,mtMul(tmp,tnow)); } return tmp;}int main(){ scanf("%d%d%d",&n,&k,&m); for (int i=0; i<n; i++) for (int j=0; j<n; j++) { scanf("%d",&a.matrix[i][j]); a.matrix[i][j]%=m; unit.matrix[i][j]=(i==j); } sa=MatrixSum(k); for (int i=0; i<n; i++) { for (int j=0; j<n; j++) printf("%d ",sa.matrix[i][j]); printf("\n"); } return 0;}
- 矩阵算法模板
- 矩阵快速幂 算法模板
- 矩阵连乘算法模板
- 求一个矩阵最大子矩阵的算法模板
- 矩阵模板
- 矩阵模板
- 矩阵模板
- 【矩阵模板】
- 矩阵模板
- 最大字段和+最大子矩阵算法模板
- 矩阵模板 51nod 算法马拉松分解问题
- 有关矩阵的模板【模板】
- 矩阵算法
- 矩阵算法
- 矩阵算法
- 矩阵类模板
- 矩阵乘法的模板
- 最大子矩阵模板
- Nginx-ngx_queue
- Android SDK下载和更新失败的解决方法!!!
- 飘逸的python - 性能调优利器profile及其意义
- jquery, json与ashx的完美结合
- 修改Eclipse启动图标
- 矩阵算法模板
- xml 转xsd->xsd转c,c++
- 判断两个对象是否是同一个对象 | Equals | ReferenceEquals |== | string 类是一个特殊的类
- Marklogic search development -1.Developing Search Applications in MarkLogic Server
- Ajax长连接
- Objective-C ,ios,iphone开发基础:自定义控件:Eg: UIButton
- HDU_4701_Game
- 实现FusionChart动态获取数据(二)
- 关系模型的基本概念