Jzzhu and Sequences (矩阵快速幂 + 取模)

Posted luckykid

tags:

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

题目链接

Jzzhu has invented a kind of sequences, they meet the following property:

            技术分享图片

You are given x and y, please calculate fn modulo 1000000007 (109?+?7).

Input

The first line contains two integers x and y (|x|,?|y|?≤?109). The second line contains a single integer n (1?≤?n?≤?2·109).

Output

Output a single integer representing fn modulo 1000000007 (109?+?7).

Examples
Input
2 3
3
Output
1
Input
0 -1
2
Output
1000000006
Note

In the first sample, f2?=?f1?+?f3, 3?=?2?+?f3, f3?=?1.

In the second sample, f2?=??-?1; ?-?1 modulo (109?+?7) equals (109?+?6).

 

AC代码:

 

技术分享图片
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 struct matrix{
 6     long long int mat[3][3];
 7 }A,B;
 8 long long int mod(long long int n){
 9     if(n > 0)
10         return n % 1000000007;
11     else if(n < 0)
12         return (n + 1000000007) % 1000000007;
13     else
14         return 0;
15 }
16 matrix mul(matrix a,matrix b){
17     matrix tmp;
18     memset(tmp.mat,0,sizeof(tmp.mat));
19     for(int i = 0;i < 3;i++)
20         for(int j = 0;j < 3;j++)
21             for(int k = 0;k < 3;k++){
22                 tmp.mat[i][j] += a.mat[i][k] * b.mat[k][j];
23                 tmp.mat[i][j] = mod(tmp.mat[i][j]);
24             }
25     return tmp;
26 }
27 matrix pow_mat(matrix a,int n){
28     matrix ans;
29     memset(ans.mat,0,sizeof(ans.mat));
30     for(int i = 0;i < 3;i++)
31         ans.mat[i][i] = 1;
32     while(n){
33         if(n & 1)
34             ans = mul(ans,a);
35         a = mul(a,a);
36         n >>= 1;
37     }
38     return ans;
39 }
40 int main(){
41     long long int x,y,n;
42     scanf("%lld%lld%lld",&x,&y,&n);
43     if(n == 1)
44         printf("%lld
",mod(x));
45     else if(n == 2)
46         printf("%lld
",mod(y));
47     else if(n == 3)
48         printf("%lld
",mod(y - x + 1000000007)); //注意这里的取模
49     else{
50         A.mat[0][0] = x,A.mat[0][1] = y,A.mat[0][2] = y - x;
51         B.mat[0][0] = 0,B.mat[0][1] = 0,B.mat[0][2] = 0;
52         B.mat[1][0] = 1,B.mat[1][1] = 0,B.mat[1][2] = -1;
53         B.mat[2][0] = 0,B.mat[2][1] = 1,B.mat[2][2] = 1;
54         B = pow_mat(B,n - 3);
55         printf("%lld
",mod(mul(A,B).mat[0][2]));
56     }
57     return 0;
58 }
View Code

 



以上是关于Jzzhu and Sequences (矩阵快速幂 + 取模)的主要内容,如果未能解决你的问题,请参考以下文章

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

CodeForces 450B Jzzhu and Sequences

(CF#257)B. Jzzhu and Sequences

Codeforces 450B Jzzhu and Sequences

B. Jzzhu and Sequences1300 / 思维 规律

Codeforces Round 450 Div2 B.Jzzhu and Sequences