牛客第五场 B 矩阵快速幂(十进制)

当指数很大的时候可以考虑用十进制快速幂。

链接

题意

标准的快速幂。

思路

以前是二进制拆分系数,现在改成十进制。

例如$2^{498} = 2^8 \times (2^{10})^9 \times (2^{100})^4$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;
#define ll long long
ll x0, x1, a, b, mod;

struct Matrix{
ll m[5][5];
};

Matrix mul(Matrix A, Matrix B){
Matrix tmp;
for(int i = 1; i <= 2; ++i)
{
for(int j = 1; j <= 2; ++j)
{
tmp.m[i][j] = 0;
for(int k = 1; k <= 2; ++k)
{
tmp.m[i][j] = (tmp.m[i][j] + A.m[i][k] * B.m[k][j]) % mod;
}
}
}
return tmp;
}
int main()
{
string s;
cin >> x0 >> x1 >> a >> b;
cin >> s >> mod;
Matrix ans,c,d,o;
ans.m[1][1] = ans.m[2][2] = 1;
ans.m[1][2] = ans.m[2][1] = 0;
c.m[1][1] = a, c.m[1][2] = b;
c.m[2][1] = 1, c.m[2][2] = 0;
d.m[1][1] = x1;
d.m[2][1] = x0;
for(int i = s.size() - 1; i >= 0; --i)
{
int num = s[i] - '0';
for(int j = 0; j < num; ++j)
ans = mul(ans, c);
o.m[1][1] = o.m[2][2] = 1;
o.m[1][2] = o.m[2][1] = 0;
for(int j = 0; j < 10; ++j)
o = mul(o, c);
c = o;
}
ans = mul(ans,d);
cout << ans.m[2][1] << '\n';
}