POJ 3233-Matrix Power Series( S = A + A^2 + A^3 + … + A^k 矩陣快速冪取模)
阿新 • • 發佈:2017-12-03
spa nta plm lines case arch lang stream 矩陣 Matrix Power Series
(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.
已知n,k,m,S = A + A2 + A3 + … + Ak. 求:S%m
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 20309 | Accepted: 8524 |
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
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
Source
POJ Monthly--2007.06.03, Huang, Jinsong題目意思:
解題思路:
模板題,快速冪取模+二分優化。
補充一個關於等比序列分治的結論:
對於
Sn=(A^1+A^2+A^3+……+A^(n-1)+A^n) mod p
當n為偶數的時候
s[n]=(1+A^(n/2))* (A^1+A^2+A^3+……+A^(n/2)) =(1+A^(n/2))*S[n/2]
當n為奇數的時候
s[n]=(1+A^((n-1)/2+1))* (A^1+A^2+A^3+……+A^(n-1)/2)+A^((n-1)/2+1]
=(1+A^((n-1)/2+1))* S[(n-1)/2] + A^((n-1)/2+1) =(1+A^(n/2+1))*S[n/2] + A^(n/2+1)
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <vector> #include <queue> #include <map> #include <algorithm> #define INF 0xfffffff using namespace std; const long long MAXN=81; long long n,mod; struct Mat { long long m[MAXN][MAXN]; }; Mat a,per; void init() { long long i,j; for(i=0; i<n; ++i) for(j=0; j<n; ++j) { cin>>a.m[i][j]; a.m[i][j]%=mod; per.m[i][j]=(i==j); } } Mat mul(Mat A,Mat B) { Mat ans;long long i,j,k; for(i=0; i<n; i++) for(j=0; j<n; j++) { ans.m[i][j]=0; for(k=0; k<n; k++) ans.m[i][j]+=(A.m[i][k]*B.m[k][j]); ans.m[i][j]%=mod; } return ans; } Mat power(long long k) { Mat p,ans=per; p=a; while(k) { if(k&1) { ans=mul(ans,p); --k; } else { k/=2; p=mul(p,p); } } return ans; } Mat add(Mat a,Mat b) { Mat c;long long i,j; for(i=0; i<n; ++i) for(j=0; j<n; ++j) c.m[i][j]=(a.m[i][j]+b.m[i][j])%mod; return c; } Mat sum(long long k) { if(k==1) return a; Mat temp,b; temp=sum(k/2); if(k&1) { b=power(k/2+1); temp=add(temp,mul(temp,b)); temp=add(temp,b); } else { b=power(k/2); temp=add(temp,mul(temp,b)); } return temp; } int main() { ios::sync_with_stdio(false); cin.tie(0); long long i,j,k; while(cin>>n>>k>>mod) { init(); Mat ans=sum(k); for(i=0; i<n; ++i) { for(j=0; j<n-1; ++j) cout<<ans.m[i][j]<<" "; cout<<ans.m[i][j]<<endl; } } return 0; }
POJ 3233-Matrix Power Series( S = A + A^2 + A^3 + … + A^k 矩陣快速冪取模)