题意:给出x,y,n,求fn。
题解:矩阵快速幂
将式子变形:
f
f
fi+1 =
f
f
fi −
f
f
fi−1
我们可以得到转移矩阵:
[
1
1
−
1
0
]
\left[ \begin{matrix} 1 & 1 \\ -1 & 0 \\ \end{matrix} \right]
[1−110]
初始矩阵
f
f
f2就是{y, x}。
然后对n=1特判即可。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int mod = 1e9 + 7;
struct Matrix {
ll mat[2][2];
Matrix operator * (const Matrix& b)const {
Matrix ans;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
ans.mat[i][j] = 0;
for (int k = 0; k < 2; k++) {
ans.mat[i][j] = (ans.mat[i][j] + mat[i][k] * b.mat[k][j] % mod + mod) % mod;
}
}
}
return ans;
}
};
Matrix q_pow(Matrix a, ll b) {
Matrix ans;
memset(ans.mat, 0, sizeof(ans.mat));
for (int i = 0; i < 2; i++) ans.mat[i][i] = 1;
while (b) {
if (b & 1) ans = ans * a;
b >>= 1;
a = a * a;
}
return ans;
}
ll x, y, n;
int main() {
scanf("%lld%lld%lld", &x, &y, &n);
if(n == 1) {
x = (x % mod + mod) % mod;
printf("%lld\n", x);
return 0;
}
Matrix ma;
ma.mat[0][0] = 1;
ma.mat[0][1] = 1;
ma.mat[1][0] = -1;
ma.mat[1][1] = 0;
ma = q_pow(ma, n - 2);
ll ans = ((ma.mat[0][0] * y % mod + ma.mat[1][0] * x % mod) % mod + mod) % mod;
printf("%lld\n", ans);
return 0;
}