UVA10689 Yet another Number Sequence —— 斐波那契、矩阵快速幂

题目链接:https://vjudge.net/problem/UVA-10689

题解:

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <cmath>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 using namespace std;
13 typedef long long LL;
14 const int INF = 2e9;
15 const LL LNF = 9e18;
16 //const int MOD = 1e9+7;
17 const int MAXN = 1e6+100;
18 
19 LL MOD;
20 const int Size = 2;
21 struct MA
22 {
23     LL mat[Size][Size];
24     void init()
25     {
26         for(int i = 0; i<Size; i++)
27         for(int j = 0; j<Size; j++)
28             mat[i][j] = (i==j);
29     }
30 };
31 
32 MA mul(MA x, MA y)
33 {
34     MA ret;
35     memset(ret.mat, 0, sizeof(ret.mat));
36     for(int i = 0; i<Size; i++)
37     for(int j = 0; j<Size; j++)
38     for(int k = 0; k<Size; k++)
39         ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD, ret.mat[i][j] %= MOD;
40     return ret;
41 }
42 
43 MA qpow(MA x, LL y)
44 {
45     MA s;
46     s.init();
47     while(y)
48     {
49         if(y&1) s = mul(s, x);
50         x = mul(x, x);
51         y >>= 1;
52     }
53     return s;
54 }
55 
56 MA tmp = {
57     1, 1,
58     1, 0
59 };
60 
61 int main()
62 {
63     LL f[2], n, m;
64     int T;
65     scanf("%d", &T);
66     while(T--)
67     {
68         scanf("%lld%lld%lld%lld",&f[0],&f[1],&n,&m);
69         if(n<2)
70         {
71             printf("%lld
", f[n]);
72             continue;
73         }
74 
75         MOD = 1;
76         while(m--) MOD *= 10;
77         MA s = tmp;
78         s = qpow(s, n-1);
79         LL ans = (1LL*s.mat[0][0]*f[1]%MOD+1LL*s.mat[0][1]*f[0]%MOD)%MOD;
80         printf("%lld
", ans);
81     }
82 }
View Code
原文地址:https://www.cnblogs.com/DOLFAMINGO/p/8413513.html