矩阵是一个很好的工具,
参考别人到博客:http://mindlee.net/2011/11/21/matrix-multiply/
经典矩阵相乘10题,大牛博客 http://www.matrix67.com/blog/archives/276/
1 /* 2 矩阵的运用很宽泛 3 */ 4 #include<iostream> 5 #include<cstdio> 6 #include<cstdlib> 7 #include<cstring> 8 #define N 100 9 #define mod 10000007 10 using namespace std; 11 12 struct Matrix 13 { 14 int mat[N][N]; 15 }M_hxl,M_tom; 16 17 18 void Matrix_ini(Matrix *cur,int len) 19 { 20 int i,j; 21 for(i=1;i<=len;i++) 22 for(j=1;j<=len;j++) 23 if(i==j) 24 cur->mat[i][j]=1; 25 else 26 cur->mat[i][j]=0; 27 } 28 29 Matrix Multiply(Matrix cur,Matrix now,int len)//矩阵相乘 30 { 31 Matrix ww; 32 int i,j,k; 33 memset(ww.mat,0,sizeof(ww.mat)); 34 for(i=1;i<=len;i++) 35 for(k=1;k<=len;k++) 36 if(cur.mat[i][k]) 37 { 38 for(j=1;j<=len;j++) 39 if(now.mat[k][j]) 40 { 41 ww.mat[i][j]+=cur.mat[i][k]*now.mat[k][j]; 42 if(ww.mat[i][j]>=mod) 43 ww.mat[i][j]%=mod; 44 } 45 } 46 return ww; 47 } 48 49 struct Matrix M_add(Matrix cur,Matrix now,int len)//矩阵相加 50 { 51 Matrix ww; 52 int i,j; 53 memset(ww.mat,0,sizeof(ww.mat)); 54 55 for(i=1;i<=len;i++) 56 for(j=1;j<=len;j++) 57 { 58 ww.mat[i][j]=cur.mat[i][j]+now.mat[i][j]; 59 if(ww.mat[i][j]>=mod) 60 ww.mat[i][j]%=mod; 61 } 62 return ww; 63 } 64 65 Matrix pow_sum1(Matrix cur,int n,int len)//矩阵快速幂 66 { 67 Matrix ww; 68 Matrix_ini(&ww,len); 69 while(n) 70 { 71 if(n&1) 72 { 73 ww=Multiply(ww,cur,len); 74 } 75 n=n>>1; 76 cur=Multiply(cur,cur,len); 77 } 78 return ww; 79 } 80 81 Matrix pow_sum2(Matrix cur,int n,int len)//A^1+A^2+A^3+A^4.... 82 { 83 int zhan[64],zlen=0,i; 84 Matrix tp1,tp2=cur,ret; 85 Matrix_ini(&ret,len); 86 while(n) 87 { 88 zhan[++zlen]=n&1; 89 n=n>>1; 90 } 91 for(i=zlen-1;i>=1;i--) 92 { 93 tp1=Multiply(tp1,M_add(tp2,ret,len),len); 94 tp2=Multiply(tp2,tp2,len); 95 if(zhan[i]) 96 { 97 tp2=Multiply(tp2,cur,len); 98 tp1=M_add(tp2,tp1,len); 99 } 100 } 101 return tp1; 102 } 103 104 int main() 105 { 106 }