首页 > 代码库 > 蓝桥杯 算法提高 递推求值

蓝桥杯 算法提高 递推求值

思路:

矩阵快速幂。

实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <vector>
 4 using namespace std;
 5 
 6 typedef long long ll;
 7 typedef vector<ll> vec;
 8 typedef vector<vec> mat;
 9 
10 const int mod = 99999999;
11 
12 mat mul(mat & a, mat & b)
13 {
14     mat c(a.size(), vec(b[0].size()));
15     for (int i = 0; i < a.size(); i++)
16     {
17         for (int k = 0; k < b.size(); k++)
18         {
19             for (int j = 0; j < b[0].size(); j++)
20             {
21                 c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod;
22             }
23         }
24     }
25     return c;
26 }
27 
28 mat pow(mat a, ll n)
29 {
30     mat b(a.size(), vec(a.size()));
31     for (int i = 0; i < a.size(); i++)
32     {
33         b[i][i] = 1;
34     }
35     while (n > 0)
36     {
37         if (n & 1)
38             b = mul(b, a);
39         a = mul(a, a);
40         n >>= 1;
41     }
42     return b;
43 }
44 
45 int main()
46 {
47     mat F(7, vec(1));
48     F[0][0] = 6;
49     F[1][0] = 1;
50     F[2][0] = 2;
51     F[3][0] = 5;
52     F[4][0] = 4;
53     F[5][0] = 3;
54     F[6][0] = 1;
55     ll n;
56     cin >> n;
57     if (n <= 3)
58     {
59         printf("%d\n", F[3-n][0]);
60         printf("%d\n", F[5-(n-1)][0]);
61         return 0;
62     }
63     mat x(7, vec(7));
64     for (int i = 0; i < 7; i++)
65     {
66         for (int j = 0; j < 7; j++)
67         {
68             x[i][j] = 0;
69         }
70     }
71     x[0][2] = 2;
72     x[0][3] = 1;
73     x[0][6] = 5;
74     x[1][0] = 1;
75     x[2][1] = 1;
76     x[3][0] = 1;
77     x[3][2] = 3;
78     x[3][5] = 2;
79     x[3][6] = 3;
80     x[4][3] = 1;
81     x[5][4] = 1;
82     x[6][6] = 1;
83     mat res(7, vec(7));
84     res = pow(x, n - 3);
85     mat fuck(7, vec(1));
86     fuck = mul(res, F);
87     printf("%d\n", fuck[0][0]);
88     printf("%d\n", fuck[3][0]);
89     return 0;
90 }

 

蓝桥杯 算法提高 递推求值