Codeforces Round #257 (Div. 2) B. Jzzhu and Sequences (矩阵快速幂)

Posted Recoder

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #257 (Div. 2) B. Jzzhu and Sequences (矩阵快速幂)相关的知识,希望对你有一定的参考价值。

题目链接:http://codeforces.com/problemset/problem/450/B

题意很好懂,矩阵快速幂模版题。

 1 /*
 2     | 1, -1 | | fn   |
 3     | 1,  0 | | fn-1 |
 4 */
 5 #include <iostream>
 6 #include <cstdio>
 7 #include <cstring>
 8 using namespace std;
 9 typedef __int64 LL;
10 LL mod = 1e9 + 7;
11 struct data {
12     LL mat[3][3];
13 };
14 
15 data operator* (data a , data b) {
16     data res;
17     for(int i = 1 ; i <= 2 ; i++) {
18         for(int j = 1 ; j <= 2 ; j++) {
19             res.mat[i][j] = 0;
20             for(int k = 1 ; k <= 2 ; k++) {
21                 res.mat[i][j] = ((a.mat[i][k]*b.mat[k][j] % mod) + res.mat[i][j]) % mod;
22             }
23         }
24     }
25     return res;
26 }
27 
28 data operator^ (data a , LL n) {
29     data res;
30     for(int i = 1 ; i <= 2 ; i++) {
31         for(int j = 1 ; j <= 2 ; j++) {
32             res.mat[i][j] = (i == j);
33         }
34     }
35     while(n) {
36         if(n & 1)
37             res = a * res;
38         a = a * a;
39         n >>= 1;
40     }
41     return res;
42 }
43 
44 int main()
45 {
46     data res;
47     LL n;
48     cin >> res.mat[2][1] >> res.mat[1][1] >> n;
49     if(n == 1) {
50         cout << (res.mat[2][1] % mod + mod) % mod << endl;
51     }
52     else if(n == 2) {
53         cout << (res.mat[1][1] % mod + mod) % mod << endl;
54     }
55     else {
56         data a;
57         a.mat[2][1] = a.mat[1][1] = 1;
58         a.mat[2][2] = 0;
59         a.mat[1][2] = -1;
60         a = a ^ (n - 2);
61         res = a * res;
62         cout << (res.mat[1][1] % mod + mod) % mod << endl;
63     }
64 }

 

以上是关于Codeforces Round #257 (Div. 2) B. Jzzhu and Sequences (矩阵快速幂)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #589 (Div. 2)E(组合数,容斥原理,更高复杂度做法为DP)

Codeforces Round #436 E. Fire(背包dp+输出路径)

[ACM]Codeforces Round #534 (Div. 2)

Codeforces Round #726 (Div. 2) B. Bad Boy(贪心)

Codeforces 257C

Codeforces 257D