Codeforces Round 450 Div2 B.Jzzhu and Sequences

B. Jzzhu and Sequences

time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output

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

![](https://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).

Examples

input

2 3
3

output

1

input

0 -1
2

output

1000000006

Note

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

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

题解

使用矩阵快速幂,构造2*2矩阵从左到右从上到下为 1,1,-1,0。代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <utility>
#define ll long long

using namespace std ;

const ll MOD = 1e9+7 ;
const int maxn = 2 ;

struct matrix{
    int m[maxn][maxn] ;
}mat ;

matrix operator *(matrix a , matrix b){
    matrix res ;
    for ( int i = 0 ; i < maxn ; i ++ ){
        for ( int j = 0 ; j < maxn ; j ++ ){
            ll temp = 0 ;
            for ( int k = 0 ; k < maxn ; k ++ ){
                temp += (a.m[i][k] % MOD * b.m[k][j] % MOD) % MOD ;
            }
            res.m[i][j] = temp % MOD ;
        }
    }
    return res ;
}

void init(){
    for ( int i = 0 ; i < maxn ; i ++ ){
        mat.m[i][i] = 1 ;
    }
    return ;
}

matrix quick_pow(matrix a, ll n){
    matrix ans = mat ;
    while (n){
        if (n & 1){
            ans = ans * a ;
        }
        a = a * a ;
        n >>= 1 ;
    }
    return ans ;
}

int main(){
    ll x , y , n ;
    while ( cin >> x >> y >> n ){
        if ( n == 1 ){
            cout << (x % MOD + MOD) % MOD << endl ;
        }else if ( n == 2 ){
            cout << (y % MOD + MOD) % MOD << endl ;
        }else{
            init() ;
            matrix temp ;
            temp.m[0][0] = 1 , temp.m[0][1] = 1 ;
            temp.m[1][0] = -1 , temp.m[1][1] = 0 ;
            temp = quick_pow(temp , n - 2) ;
            matrix ans ;
            ans.m[0][0] = y , ans.m[0][1] = x ;
            ans = ans * temp ;
            cout << (ans.m[0][0] % MOD + MOD) % MOD << endl ;
        }
    }
    return 0 ;
}

猜你喜欢

转载自www.cnblogs.com/Cantredo/p/10041712.html