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).
The first line contains two integers x and y (|x|, |y| ≤ 10^9). The second line contains a single integer n (1 ≤ n ≤ 2·10^9).
Output a single integer representing fn modulo 1000000007 (10^9 + 7).
2 3 3
1
0 -1 2
1000000006
In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.
In the second sample, f2 = - 1; - 1 modulo (10^9 + 7) equals (10^9 + 6).
问题链接:CodeForces-450B Jzzhu and Sequences
问题简述:(略)
问题分析:
方法一:
依据题意,fi+1=fi-fi-1。故:
f1=x, f2=y, f3=y-x,f4=-x, f5=-y, f6=x-y, f7=x, f8=y, ......
这个数列每6项值出现循环。
以上分析可得到f0=f6=x-y。
方法二:
用矩阵快速幂实现。
程序说明:
程序中都是套路。
题记:(略)
参考链接:(略)
AC的C++语言程序(方法一)如下:
/* CodeForces-450B Jzzhu and Sequences */
#include <iostream>
using namespace std;
const int MOD = 1000000007;
const int N = 6;
int ans[N];
int main()
{
int x, y, n;
cin >> x >> y >> n;
// Init ans
ans[0] = x - y;
ans[1] = x;
ans[2] = y;
ans[3] = y - x;
ans[4] = -x;
ans[5] = - y;
int result = ans[n % N];
if(result >= 0)
cout << result % MOD << endl;
else
cout << (result % MOD + MOD) % MOD << endl;
return 0;
}
AC的C++语言程序(方法二)如下:
/* CodeForces-450B Jzzhu and Sequences */
#include <iostream>
#include <string.h>
using namespace std;
typedef long long LL;
const int MOD = 1e9+7;
const int N = 2;
struct Matrix
{
LL m[N][N];
Matrix()
{
memset(m, 0, sizeof(m));
}
// 矩阵相乘
Matrix operator * (const Matrix& y)
{
Matrix z;
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
for(int k=0; k<N; k++) {
z.m[i][j] += m[i][k] * y.m[k][j] % MOD;
z.m[i][j] %= MOD;
}
return z;
}
};
// 矩阵快速幂
Matrix Matrix_Powmul(Matrix x, int m)
{
Matrix z;
z.m[0][1] = z.m[1][0] = 0;
z.m[0][0] = z.m[1][1] = 1;
while(m) {
if(m & 1)
z = z * x;
x = x * x;
m >>= 1;
}
return z;
}
int main()
{
int x, y, n;
int result;
cin >> x >> y >> n;
if(n == 1)
result = x;
else if(n == 2)
result = y;
else {
Matrix a;
a.m[0][0] = 0;
a.m[1][0] = -1;
a.m[0][1] = a.m[1][1] =1;
Matrix t = Matrix_Powmul(a, n - 2);
result = (x * t.m[1][0] + y * t.m[1][1]) % MOD;
}
if(result >= 0)
cout << result % MOD << endl;
else
cout << (result % MOD + MOD) % MOD << endl;
return 0;
}