线性代数(矩阵乘法):POJ 3233 Matrix Power Series
2016-06-07 20:23
507 查看
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
Sample Output
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 一道比较有意思的水题,水一水更健康!
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int maxn=50; int mod,n,K; struct Matrix{ int mat[maxn][maxn]; Matrix(){ memset(mat,0,sizeof(mat)); } Matrix operator +(Matrix a){ Matrix r; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) (r.mat[i][j]=(mat[i][j]+a.mat[i][j])%mod)%=mod; return r; } Matrix operator *(Matrix a){ Matrix r; for(int i=1,s;i<=n;i++) for(int k=1;k<=n;k++){ s=mat[i][k]; for(int j=1;j<=n;j++) (r.mat[i][j]+=(s*a.mat[k][j])%mod)%=mod; } return r; } Matrix operator ^(int k){ Matrix r,x; for(int i=1;i<=n;i++) r.mat[i][i]=1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) x.mat[i][j]=mat[i][j]; while(k){ if(k&1) r=r*x; k>>=1; x=x*x; } return r; } }A,B,ans; Matrix Solve(int k){ if(k==1)return A; if(k%2)return A+A*Solve(k-1); else return ((A^(k/2))+B)*Solve(k/2); } int main(){ #ifndef ONLINE_JUDGE //freopen("","r",stdin); //freopen("","w",stdout); #endif scanf("%d%d%d",&n,&K,&mod); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&A.mat[i][j]); for(int i=1;i<=n;i++) B.mat[i][i]=1; ans=Solve(K); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) printf("%d ",ans.mat[i][j]); printf("\n"); } return 0; }
相关文章推荐
- 【Linux】启动引导程序--grub及其配置文件
- 乐学成语2
- 机房收费系统 问题(一)——机房运行准备工作
- redis-集群安装(2)变两重冗余为三重
- spring+springMVC集成(annotation方式)
- JQuery开发7-网页中禁用鼠标右键单击和文本选择
- 第九周项目一深复制体验(2)
- AngularJS 用promises和$q处理异步调用
- Decorator装饰者设计模式
- HDU 2191 多重背包转01背包
- KMP
- 给你一个长度为N的链表。N很大,但你不知道N有多大。你的任务是从这N个元素中随机取出k个元素
- C++ 笔记4:指针函数
- XML.可扩展标记语言.就知道你不知道英文全称
- volley(5) 参数total_remain:totalqty, data:[{ bar_status:XX , bar_code: "XX",bar_remain:XX, bar_whcode:"XX" , bar_prodcode:"XX",bar_id:XX,bar_location: "XX", pr_detail: "XX" , bar_batchcode:method:POST
- 求割边模板(tarjan)
- CentOS 6.5 64位下安装Redis
- 二维数组传递参数问题
- 浅解Linux的启动流程
- C#获取当前行号