CodeForces 450B
time limit per test
1 secondmemory limit per test
256 megabytesinput
standard inputoutput
standard outputJzzhu has invented a kind of sequences, they meet the following property:
![](http://codeforces.com/predownloaded/55/53/5553125ed3b40d54293e6c3b9dac2692d9f2a964.png)
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).
Sample test(s)
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).
/** 题意:f[i] = f[i-1] + f[i+1] 做法:矩阵 如题要求建一个二维矩阵, 0 1 -1 0 然后求解 **/ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define SIZE 2 #define MOD 1000000007 #define clr( a, b ) memset( a, b, sizeof(a) ) typedef long long LL; struct Mat { LL mat[ SIZE ][ SIZE ]; int n; Mat( int _n ) { n = _n; clr( mat, 0 ); } void init() { for( int i = 0; i < n; ++i ) for( int j = 0; j < n; ++j ) mat[i][j] = ( i == j ); } Mat operator * ( const Mat &b ) const { Mat c( b.n ); for( int k = 0; k < n; ++k ) for( int i = 0; i < n; ++i ) if( mat[i][k] ) for( int j = 0; j < n; ++j ) c.mat[i][j] = ( c.mat[i][j] + mat[i][k] * b.mat[k][j] ) % MOD; return c; } }; Mat fast_mod( Mat a, int b ) { Mat res( a.n ); res.init(); while( b ) { if( b & 1 ) res = res * a; a = a * a; b >>= 1; } return res; } int main() { LL x, y, n, res; scanf( "%lld %lld %lld", &x, &y, &n ); if( n == 1 ) { printf( "%lld\n", ( x % MOD + MOD ) % MOD ); } else if( n == 2 ) { printf( "%lld\n", ( y % MOD + MOD ) % MOD ); } else { n -= 2; Mat C( 2 ); C.mat[0][0] = 0; C.mat[0][1] = 1; C.mat[1][0] = -1; C.mat[1][1] = 1; C = fast_mod( C, n ); res = ( ( x * C.mat[1][0] + y * C.mat[1][1] )% MOD + MOD ) % MOD; printf( "%lld\n", res ); } return 0; }