Matrix Power Series
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cmath>5#include <algorithm>6#include <string>7#include <vector>8#include <Set>9#include <map>Ten#include <stack> One#include <queue> A#include <sstream> -#include <iomanip> - using namespacestd; thetypedefLong LongLL; - Const intinf=0x4fffffff; - Const Doubleexp=1e-5; - Const intms= to; + Const intSize= +; - + intN,k,mod; Atypedef vector<vector<int> >Mat; at - Mat A; - //Calc A*b - -Mat Mul (Mat &a,mat &B) - { inMat C (A.size (),vector<int> (b[0].size ())); - to for(intI=0; I<a.size (); i++) + { - for(intk=0; K<b.size (); k++) the { * for(intj=0; j<b[0].size (); j + +) $ {Panax NotoginsengC[i][j]= (c[i][j]+ (LL) a[i][k]*b[k][j])%mod;//Note Overflow - } the } + } A returnC; the } + - //Calc A^n $ $Mat Pow (Mat A,intN) - { -Mat B (A.size (),vector<int> (a[0].size ())); the for(intI=0; I<a.size (); i++) -b[i][i]=1;Wuyi while(n>0) the { - if(n&1) Wub=Mul (b,a); -A=Mul (a,a); Aboutn>>=1; $ } - returnB; - } - A voidSolve () + { theMat B (2*n,vector<int> (2*n));//Init 0 - //b_init (); $ for(intI=0; i<n;i++) the { the for(intj=0; j<n;j++) theb[i][j]=A[i][j]; theb[n+i][i]=b[n+i][n+i]=1; - } inB=pow (b,k+1); the //ans=s[k+1]-1; the for(intI=0; i<n;i++) About { the for(intj=0; j<n;j++) the { the if(j) +printf" "); - inta=b[n+i][j]%MoD; the if(i==j)BayiA= (a+mod-1)%MoD; theprintf"%d", a); the } -printf"\ n"); - } the } the the intMain () the { -scanf"%d%d%d",&n,&k,&MoD); the a.resize (n); the for(intI=0; i<n;i++) the a[i].resize (n);94 for(intI=0; i<n;i++) the for(intj=0; j<n;j++) thescanf"%d",&a[i][j]); the solve ();98 return 0; About}
S = A + A2 + A3 + ... + Ak. (Push matrix formula + matrix power operation)