CodeForces 450B 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).

#include<cstdio>
#include<string>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<map>
#include<cctype>
#include<stack>
#include<sstream>
#include<list>
#include<assert.h>
#include<bitset>
#include<numeric>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define rep(i,a,b) for(int i=(a); i<(b); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
#define mod 1000000007
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int maxn = 1e5 + 20;
const int maxm = 1e6 + 10;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int dx[] = {-1,1,0,0,1,1,-1,-1};
const int dy[] = {0,0,1,-1,1,-1,1,-1};
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
#define ll long long
ll x,y,n,ans;
ll a[2][2],b[2][2];
ll res[2][2];
ll e[2][2],c[2][2];

void mul(ll a[2][2], ll b[2][2])
{

    ms(c,0);
    rep(i,0,2) rep(j,0,2) rep(k,0,2)  c[i][j]+=(a[i][k]*b[k][j])%mod, c[i][j]%=mod;
    rep(i,0,2) rep(j,0,2) a[i][j]=c[i][j];
}

void Pow(ll n)
{

    ms(e,0);
    rep(i,0,2) e[i][i]=1;
    while(n)
    {
        if(n&1)
            mul(e,a);
        mul(a,a);
        n>>=1;
    }
}

int main()
{

    while(cin>>x>>y>>n)
    {
        a[0][0]=1;a[0][1]=-1;
        a[1][0]=1;a[1][1]=0;
        if (n==1)
        printf("%lld\n", (x % mod + mod) % mod);
        else if(n==2)
            printf("%lld\n",(y % mod + mod) % mod);
        else{
            Pow(n-2);
            ll res=e[0][0]*y%mod + e[0][1]*x%mod;
            printf("%lld\n", (res%mod+mod)%mod);
        }
    }
    return 0;
}
posted @ 2018-05-23 21:37  Roni_i  阅读(230)  评论(0编辑  收藏  举报