码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-04 11:15:32      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:contains   prope   contain   target   div   sam   tle   class   com   

题目链接

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\n",mod(x));
45     else if(n == 2)
46         printf("%lld\n",mod(y));
47     else if(n == 3)
48         printf("%lld\n",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\n",mod(mul(A,B).mat[0][2]));
56     }
57     return 0;
58 }
View Code

 

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

标签:contains   prope   contain   target   div   sam   tle   class   com   

原文地址:https://www.cnblogs.com/Luckykid/p/9740329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!