快速冪和矩陣快速冪模板
阿新 • • 發佈:2017-09-23
style class 計算 res can scan urn oid 模板
快速冪模板:
ll qmod(ll x,ll n,ll mod) { ll res=1; while(n){ if(n&1) res=(res*x)%mod; x=(x*x)%mod; n/=2; } return res; }
例題:hdu 1097
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespacehdu 1097std; typedef long long ll; const ll mod=10; ll qmod(ll x,ll n) { ll res=1; while(n){ if(n&1) res=(res*x)%mod; x=(x*x)%mod; n/=2; } return res; } int main() { ll a,b; while(cin>>a>>b) { cout<<qmod(a,b)<<endl; }return 0; }
矩陣快速冪:
1 mat mul(mat &A, mat &B) 2 { 3 mat C(A.size(), vec(B[0].size()));///分配大小,A的行,B的列 4 for (int i = 0; i<A.size(); i++) ///矩陣A的行 5 for (int k = 0; k<B.size(); k++) ///矩陣B的行 6 for (int j = 0; j<B[0].size(); j++) ///矩陣B的列 7 C[i][j] = (C[i][j] + A[i][k] * B[k][j] % mod + mod) % mod;8 return C; 9 } 10 ///計算A^n 11 mat pow(mat A, LL n) 12 { 13 mat B(A.size(), vec(A.size()));///和矩陣A的大小相同 14 for (int i = 0; i<A.size(); i++) 15 B[i][i] = 1; 16 while (n>0) 17 { 18 if (n & 1) B = mul(B, A); 19 A = mul(A, A); 20 n >>= 1; 21 } 22 return B; 23 } 24 void solve() 25 { 26 mat A(2, vec(2));///2*2的矩陣 27 A[0][0] = 1; 28 A[0][1] = 1; 29 A[1][0] = 1; 30 A[1][1] = 0; 31 A = pow(A, n); 32 printf("%d\n", (A[1][0] % mod - 1 + mod) % mod); 33 }
例題:求F(2n+3)-1
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 const int mod = 998244353; 7 typedef long long LL; 8 LL n; 9 typedef vector<LL>vec; 10 typedef vector<vec>mat; 11 mat mul(mat &A, mat &B) 12 { 13 mat C(A.size(), vec(B[0].size()));///分配大小,A的行,B的列 14 for (int i = 0; i<A.size(); i++) ///矩陣A的行 15 for (int k = 0; k<B.size(); k++) ///矩陣B的行 16 for (int j = 0; j<B[0].size(); j++) ///矩陣B的列 17 C[i][j] = (C[i][j] + A[i][k] * B[k][j] % mod + mod) % mod; 18 return C; 19 } 20 ///計算A^n 21 mat pow(mat A, LL n) 22 { 23 mat B(A.size(), vec(A.size()));///和矩陣A的大小相同 24 for (int i = 0; i<A.size(); i++) 25 B[i][i] = 1; 26 while (n>0) 27 { 28 if (n & 1) B = mul(B, A); 29 A = mul(A, A); 30 n >>= 1; 31 } 32 return B; 33 } 34 void solve() 35 { 36 mat A(2, vec(2));///2*2的矩陣 37 A[0][0] = 1; 38 A[0][1] = 1; 39 A[1][0] = 1; 40 A[1][1] = 0; 41 A = pow(A, n); 42 printf("%d\n", (A[1][0] % mod - 1 + mod) % mod); 43 } 44 int main() 45 { 46 while (~scanf("%lld", &n)) 47 { 48 n = 2 * n + 3; 49 solve(); 50 } 51 }http://www.cnblogs.com/zxhyxiao/p/7577282.html
快速冪和矩陣快速冪模板