当前位置: 代码迷 >> 综合 >> Jzzhu and Sequences
  详细解决方案

Jzzhu and Sequences

热度:69   发布时间:2024-01-28 06:42:59.0

Jzzhu has invented a kind of sequences, they meet the following property:
f1 = x, f2 = y, when i>=2 , fi = fi-1 + fi+1
You are given x and y, please calculate f n 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 f n modulo 1000000007 (109?+?7).

Examples
Input

2 3
3
Output
1
Input
0 -1
2
Output
1000000006
Note
In the first sample, f 2?=?f 1?+?f 3, 3?=?2?+?f 3, f 3?=?1.

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

大致题意:给你f1,f2,任意fi = fi-1+fi+1,求fn
思路:fi+1 = fi - fi-1 => fi = fi-1 - fi-2,然后用矩阵快速幂,递推即可
在这里插入图片描述

#include <iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;struct matrix
{ll x[105][105];ll n, m;matrix(){memset(x, 0, sizeof(x));}
};int n;matrix multiply(matrix &a, matrix &b)
{matrix c;c.n = a.n;c.m = b.m;for(int i = 1; i <= a.n; i++){for(int j = 1; j <= a.m; j++){for(int k = 1; k <= a.m; k++){c.x[i][j] += a.x[i][k] * b.x[k][j];c.x[i][j] %= mod;while(c.x[i][j] < 0)c.x[i][j] += mod;}}}return c;
}matrix mpow(matrix &a, ll m)
{matrix res;/*结果矩阵*/matrix change;/*递推矩阵*/change.n = change.m = 2;change.x[1][1] = 0;change.x[1][2] = -1;change.x[2][1] = 1;change.x[2][2] = 1;res = a;while(m > 0){if(m & 1)res = multiply(res, change);change = multiply(change, change);m >>= 1;}return res;
}int main()
{ll x, y;scanf("%lld%lld", &x, &y);scanf("%lld", &n);matrix M, a;a.x[1][1] = x;a.x[1][2] = y;a.n = 1;a.m = 2;if(n == 1){ll re = x;if(re < 0)re += mod;printf("%lld", re);return 0;}else if(n == 2){ll re = y;while(re < 0)re += mod;printf("%lld", re);return 0;}M = mpow(a, n-2);/*记的要mod*/ll re = M.x[1][2];re %= mod;while(re < 0)re += mod;cout<<re<<endl;return 0;
}
  相关解决方案