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   一道比较有意思的水题,水一水更健康!
 #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=;
int mod,n,K;
struct Matrix{
int mat[maxn][maxn];
Matrix(){
memset(mat,,sizeof(mat));
} Matrix operator +(Matrix a){
Matrix r;
for(int i=;i<=n;i++)
for(int j=;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=,s;i<=n;i++)
for(int k=;k<=n;k++){
s=mat[i][k];
for(int j=;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=;i<=n;i++)
r.mat[i][i]=;
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
x.mat[i][j]=mat[i][j];
while(k){
if(k&)
r=r*x;
k>>=;
x=x*x;
}
return r;
}
}A,B,ans;
Matrix Solve(int k){
if(k==)return A;
if(k%)return A+A*Solve(k-);
else return ((A^(k/))+B)*Solve(k/);
}
int main(){
#ifndef ONLINE_JUDGE
//freopen("","r",stdin);
//freopen("","w",stdout);
#endif
scanf("%d%d%d",&n,&K,&mod);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
scanf("%d",&A.mat[i][j]); for(int i=;i<=n;i++)
B.mat[i][i]=; ans=Solve(K); for(int i=;i<=n;i++){
for(int j=;j<=n;j++)
printf("%d ",ans.mat[i][j]);
printf("\n");
}
return ;
}

最新文章

  1. chrome使用技巧(看了定不让你失望)
  2. Ubuntu环境搭建系列—Chrome/JDK/Android篇
  3. Nginx负载均衡配置
  4. 【分块】【树上莫队】bzoj1086 bzoj3052
  5. oracle 做算法 数据为空时,默认为0
  6. [moka同学摘录]Yii2 csv数据导出扩展
  7. Ado.net 通用访问类
  8. android 学习随笔十七(服务 )
  9. ubuntu 登录循环
  10. POJ 2184 Cow Exhibition (01背包的变形)
  11. 函数buf_page_address_fold
  12. APPCAN学习笔记001---app高速开发AppCan.cn平台概述
  13. for惠普2013实习生
  14. Could not resolve view with name &#39;***&#39; in servlet with name &#39;dispatcher&#39;
  15. iOS 开发 Tips
  16. 【C++】读取参数的类
  17. mvc4+entityFramework5 发布时遇到的纠结问题
  18. Lucene Query In Kibana
  19. python中由于中文路径引起的os.path.isfile(imgpath) == False问题
  20. 【Python023/024--递归】

热门文章

  1. 编程基础-msdn编程指南笔记
  2. java构造函数也可以用private开头
  3. Android Listview with different layout for each row
  4. listview的动态加载数据问题
  5. javascript社交平台分享-新浪微博、QQ微博、QQ好友、QQ空间、人人网
  6. Error Creating Deployment 有关Tomcat配置问题
  7. Java 可变参数
  8. 一句实现jquery导航栏
  9. unix-环境高级编程-读书笔记与习题解答-第三篇
  10. STM32学习笔记——USART串口(向原子哥和火哥学习)