Hdu--4990(矩阵快速幂,模板)
2014-09-08 00:26:02
贴一发矩阵快速幂的模板。
1 /************************************************************************* 2 > File Name: b.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Sun 07 Sep 2014 10:50:06 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 typedef long long ll; 16 const int INF = 1 << 29; 17 18 int n,m; 19 20 struct Mx{ 21 int a[2][2]; 22 void clear(){ a[0][0] = a[0][1] = a[1][0] = a[1][1] = 0;} 23 void stand(){ a[0][0] = a[1][1] = 1,a[0][1] = a[1][0] = 0;} 24 Mx operator * (const Mx &b) const{ 25 Mx c; 26 c.clear(); 27 for(int k = 0; k < 2; ++k) 28 for(int i = 0; i < 2; ++i) 29 for(int j = 0; j < 2; ++j){ 30 c.a[i][j] = (c.a[i][j] + (ll)a[i][k] * b.a[k][j]) % m; 31 } 32 return c; 33 } 34 }; 35 36 ll Mx_pow(int n){ 37 Mx y,a; 38 y.stand(); 39 a.a[0][0] = 4,a.a[0][1] = a.a[1][1] = 1,a.a[1][0] = 0; 40 while(n){ 41 if(n & 1) y = y * a; 42 if(n >>= 1) a = a * a; 43 } 44 return y.a[0][1] % m; 45 } 46 47 int main(){ 48 while(scanf("%d%d",&n,&m) != EOF){ 49 int ans = Mx_pow((n + 1) / 2); 50 if((n & 1) == 0) ans *= 2; 51 printf("%d\n",ans % m); 52 } 53 return 0; 54 }