矩阵
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 7 Accepted Submission(s) : 4
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
假设你有一个矩阵,有这样的运算A^(n+1) = A^(n)*A (*代表矩阵乘法)
现在已知一个n*n矩阵A,S = A+A^2+A^3+...+A^k,输出S,因为每一个元素太大了,输出的每个元素模10
Input
先输入一个T(T<=10),每组一个n,k(1<=n<=30, k<=1000000)
Output
输出一个矩阵,每个元素模10(行末尾没有多余空格)
Sample Input
1 3 2 0 2 0 0 0 2 0 0 0
Sample Output
0 2 4 0 0 2 0 0 0 矩阵快速幂 + 等比数列二分求和AC
1 #include <cstdio> 2 #include <cmath> 3 #include <cstring> 4 #include <cstdlib> 5 #include <iostream> 6 #include <sstream> 7 #include <algorithm> 8 #include <string> 9 #include <queue> 10 #include <vector> 11 using namespace std; 12 const int maxn= 1e5+10; 13 const double eps= 1e-6; 14 const int inf = 0x3f3f3f3f; 15 const int mod =10; 16 typedef long long ll; 17 int n,m; 18 struct matrix 19 { 20 int m[35][35]; 21 matrix() 22 { 23 memset(m,0,sizeof(m)); 24 } 25 }; 26 matrix operator *(const matrix &a,const matrix &b) 27 { 28 matrix c; 29 for(int i=1;i<=n;i++) 30 for(int j=1;j<=n;j++) 31 { 32 c.m[i][j]=0; 33 for(int k=1;k<=n;k++) 34 c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%mod; 35 } 36 return c; 37 } 38 matrix quick(matrix base,int pow) 39 { 40 matrix a; 41 for(int i=1;i<=n;i++) a.m[i][i]=1; 42 while(pow) 43 { 44 if(pow&1) a=a*base; 45 base=base*base; 46 pow>>=1; 47 } 48 return a; 49 } 50 matrix sum(matrix a,matrix b) 51 { 52 for(int j=1;j<=n;j++) 53 for(int k=1;k<=n;k++) 54 a.m[j][k]=(a.m[j][k]+b.m[j][k])%mod; 55 return a; 56 } 57 matrix solve(matrix x,int y) 58 { 59 matrix a,s; 60 if(y==1) 61 return x; 62 a=solve(x,y/2); 63 s=sum(a,a*quick(x,y/2)); 64 if(y&1) 65 s=sum(s,quick(x,y)); 66 return s; 67 } 68 int main() 69 { 70 int t; 71 scanf("%d",&t); 72 while(t--) 73 { 74 scanf("%d %d",&n,&m); 75 matrix a; 76 for(int i=1;i<=n;i++) 77 for(int j=1;j<=n;j++) 78 scanf("%d",&a.m[i][j]); 79 matrix ans=solve(a,m); 80 for(int i=1;i<=n;i++) 81 { 82 for(int j=1;j<=n;j++) 83 { 84 if(j==n) 85 printf("%d\n",ans.m[i][j]); 86 else 87 printf("%d ",ans.m[i][j]); 88 } 89 } 90 91 } 92 }
时间: 2024-10-12 03:01:08