Matrix Power Series
Matrix Power Series
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions:28021 | Accepted: 11426 |
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
题意就是求矩阵的幂的和.
可以用二分法来写.
这里我用构造矩阵来写.
B=|AA|
| 0 1|
B^2 = |A^2 A+A^2|
| 0 1 |
...
以此类推..
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #define ll long long int 5 using namespace std; 6 typedef vector<ll> vec; 7 typedef vector<vec> mat; 8 int mod; 9 10 mat mul(mat &a,mat &b){ 11 mat c(a.size(),vec(b[0].size())); 12 for(int i=0;i<a.size();i++){ 13 for(int j=0;j<b[0].size();j++){ 14 for(int k=0;k<b.size();k++){ 15 c[i][j] = (c[i][j]+a[i][k]*b[k][j])%mod; 16 } 17 } 18 } 19 return c; 20 } 21 22 mat pow(mat a,int n){ 23 mat c(a.size(),vec(a.size())); 24 for(int i=0;i<a.size();i++) 25 c[i][i] = 1; 26 while(n){ 27 if(n&1) 28 c = mul(c,a); 29 a = mul(a,a); 30 n>>=1; 31 } 32 return c; 33 } 34 35 int n,k; 36 int main(){ 37 scanf("%d%d%d",&n,&k,&mod);; 38 mat a(n*2,vec(n*2)); 39 for(int i=0;i<n;i++){ 40 for(int j=0;j<n;j++){ 41 scanf("%d",&a[i][j]); 42 a[i][j+n] = a[i][j]; 43 } 44 } 45 for(int i=n;i<n*2;i++) 46 a[i][i] = 1; 47 a = pow(a,k); 48 for(int i=0;i<n;i++){ 49 for(int j=n;j<n*2;j++){ 50 cout<<a[i][j]<<" "; 51 } 52 cout<<endl; 53 } 54 return 0; 55 }