HDU4565

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4565

题目大意:

  给出a,b,n,m,求出下式中的 Sn.

                                                    

解题思路:

  

 

AC代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 typedef long long ll;
 6 struct Matrix{
 7     ll mat[2][2];
 8 };
 9 Matrix Multiply(Matrix x,Matrix y,ll mod){
10     Matrix temp;
11     memset(temp.mat,0,sizeof(temp.mat));
12     for(int i=0;i<2;i++){
13         for(int j=0;j<2;j++){
14             for(int k=0;k<2;k++){
15                 temp.mat[i][j]+=(x.mat[i][k]*y.mat[k][j]);
16                 temp.mat[i][j]%=mod;
17             }
18         }
19     }
20     return temp;
21 }
22 Matrix Fast_Power(Matrix a,ll m,ll mod){
23     Matrix res;
24     memset(res.mat,0,sizeof(res.mat));
25     for(int i=0;i<2;i++)    res.mat[i][i]=1;
26     while(m){
27         if(m&1) res=Multiply(res,a,mod);
28         m>>=1;
29         a=Multiply(a,a,mod);
30     }
31     return res;
32 }
33 int main()
34 {
35     ll a,b,n,m;
36     while(scanf("%lld%lld%lld%lld",&a, &b, &n, &m)==4){
37         Matrix l={  a,1,
38                     0,0 };
39         Matrix r={  a,1,
40                     b,a };
41         r=Fast_Power(r,n-1,m);
42         l=Multiply(l,r,m);
43         printf("%lld\n",(l.mat[0][0]*2)%m);
44     }
45     return 0;
46 }
View Code