CodeForces450B Jzzhu and Sequences (矩阵快速幂)

来源:互联网 发布:软件性质 编辑:程序博客网 时间:2024/06/11 13:45

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).

Example
Input
2 33
Output
1
Input
0 -12
Output
1000000006
Note

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

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




题目大意:输入x,y,n,f(1) = x, f(2) = y,求f(n);

思路:从题意可知:f(n) = f(n-1) + f(n+1), 即f(n+1) = f(n) - f(n-1)....看上去是不是特别想斐波那契数列。。。。可以求得系数矩阵 A = {{1,-1}{1,0}},所以可以通过矩阵快速幂来求出f[n]。

x[1] = {f[2],-f[1]},所以x[n] = {f[n+1],-f[n]},,因为要求f[n]的值,所以我们要求的是x[n-1],即A^(n-2) * X1 = X(n-1),所以calcu(n-2)。

代码如下:

#include <bits/stdc++.h>using namespace std;#define ll long longconst ll mod = 1e9+7;ll x,y,n;struct Matrix{ll a[3][3];}ori,res;void Init(){ori.a[0][0] = ori.a[1][0] = 1;ori.a[0][1] = -1;ori.a[1][1] = 0;memset(res.a,0,sizeof(res));for(int i = 0; i < 2; i ++) res.a[i][i] = 1;}Matrix multiply(Matrix x, Matrix y){Matrix temp;memset(temp.a,0,sizeof(temp.a));for(int i = 0; i < 2; i ++){for(int j = 0; j < 2; j ++){for(int k = 0; k < 2; k ++){temp.a[i][j] += (x.a[i][k] * y.a[k][j] % mod);temp.a[i][j] %= mod;}}}return temp;}void calcu(int n){Matrix temp;while(n){if(n & 1) res = multiply(res,ori);n >>= 1;ori = multiply(ori,ori);}memset(temp.a,0,sizeof(temp.a));temp.a[0][0] = y; temp.a[1][0] = x;res = multiply(res,temp);printf("%lld\n",(res.a[0][0] + mod) % mod);}int main(){while(~scanf("%lld%lld%lld",&x,&y,&n)){Init();if(n == 1) printf("%lld\n",(x + mod) % mod);else if(n == 2) printf("%lld\n",(y + mod) % mod);else calcu(n-2);//f(n+1) = f(n) -f(n-1),}return 0;}




阅读全文
0 0
原创粉丝点击