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

Codeforces Round 450 Div2 B.Jzzhu and Sequences

时间:2018-11-30 00:43:59      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:+=   end   com   bsp   cout   input   queue   als   mod   

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 ;
}

Codeforces Round 450 Div2 B.Jzzhu and Sequences

标签:+=   end   com   bsp   cout   input   queue   als   mod   

原文地址:https://www.cnblogs.com/Cantredo/p/10041712.html

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