2017 ECJTU ACM程序設計競賽 矩陣快速冪+二分
阿新 • • 發佈:2017-11-22
input ostream limit urn n) font -- truct i++
現在已知一個n*n矩陣A,S = A+A^2+A^3+...+A^k,輸出S,因為每一個元素太大了,輸出的每個元素模10
先輸入一個T(T<=10),每組一個n,k(1<=n<=30, k<=1000000)
矩陣
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
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 intm[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 }
2017 ECJTU ACM程序設計競賽 矩陣快速冪+二分