Matrix Power Series(矩阵快速幂+求幂和)
2015-08-05 16:32
405 查看
Link:http://poj.org/problem?id=3233
AC code:
Matrix Power Series
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 |
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<queue> #include<map> #define LL long long #define MAXN 1000010 using namespace std; const int INF=0x3f3f3f3f; //----以下为矩阵快速幂模板-----// //const int mod=1000;//模3,故这里改为3即可 int mod=1000; const int NUM=32;//定义矩阵能表示的最大维数 int N;//N表示矩阵的维数,以下的矩阵加法、乘法、快速幂都是按N维矩阵运算的 struct Mat{//矩阵的类 int a[NUM][NUM]; Mat(){memset(a,0,sizeof(a));} void init()//将其初始化为单位矩阵 { memset(a,0,sizeof(a)); for(int i=0;i<NUM;i++) { a[i][i]=1; } } }; Mat add(Mat a,Mat b)//(a+b)%mod 矩阵加法 { Mat ans; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { ans.a[i][j]=(a.a[i][j]%mod)+(b.a[i][j]%mod); ans.a[i][j]%=mod; } } return ans; } Mat mul(Mat a,Mat b) //(a*b)%mod 矩阵乘法 { Mat ans; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { ans.a[i][j]=0; for(int k=0;k<N;k++) { ans.a[i][j]=(ans.a[i][j]%mod)+(a.a[i][k]%mod)*(b.a[k][j]%mod); } ans.a[i][j]%=mod; } } return ans; } Mat power(Mat a,int num)//(a^n)%mod 矩阵快速幂 { Mat ans; ans.init(); while(num) { if(num&1) { ans=mul(ans,a); } num>>=1; a=mul(a,a); } return ans; } Mat pow_sum(Mat a,int num)//(a+a^2+a^3....+a^n)%mod 矩阵的幂和 { int m; Mat ans,pre; if(num==1) return a; m=num/2; pre=pow_sum(a,m); ans=add(pre,mul(pre,power(a,m))); if(num&1) ans=add(ans,power(a,num)); return ans; } void output(Mat a)//输出矩阵 { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { printf("%d%c",a.a[i][j],j==N-1?'\n':' '); } } } //----以上为矩阵快速幂模板-----// int main() { //freopen("D:\in.txt","r",stdin); int n,m,i,j,T,k; scanf("%d%d%d",&n,&k,&m); Mat A,S; N=n; mod=m; for(i=0;i<N;i++) { for(j=0;j<N;j++) { scanf("%d",&A.a[i][j]); } } S=pow_sum(A,k); output(S); return 0; }
相关文章推荐
- 10个加速Table Views开发的Tips
- 旋转字符串
- 一个批量安装文件夹下(包括子目录下)全部的Android apk文件批处理脚本
- Openjudge1288 The Rotation Game(dfs)
- Java游戏之碰撞检测
- webuploader
- hdu 2054 A == B ? (java)
- 字典中添加不同类型的值(ios)
- 举例详解Python中yield生成器的用法
- LeetCode #26 Remove Duplicates from Sorted Array
- NUC100RE3AN串口驱动库修改
- iOS App提交指南-协议、税务和银行业务
- 基于caffe特征可视化 以及 用训练好的模型进行分类
- JVM参数分析(精)
- OA强大的考勤管理
- lingo中对start(@wrap(J+I+2,7))) >= required(J))的理解
- 简洁的发包--网络游戏
- 制作网页雪花飘飘效果
- html的标签3
- zoj 2676 Network Wars 最小割+0-1分数规划