CodeForces 450B Jzzhu and Sequences
题目链接:CodeForces 450B Jzzhu and Sequences
题目大意:
已知\(x\)和\(y\),给你\(n\),求\(f_n\%1e9+7\)。
题解:
找规律
因为\(f_i=f_{i-1} + f_{i+1}\),所以\(f_{i+1} = f_i-f_{i-1}\),即\(f_i=f_{i-1}-f_{i-2}\)。
寻找规律发现这个数列每\(6\)个数为一个循环,则直接输出\(n\%6\)之后对应的值就行了。
#include <iostream>
using namespace std;
const int mod = 1e9 + 7;
int main() {
long long f[7], n;
cin >> f[1] >> f[2] >> n;
for (int i = 3; i <= 6; ++i) f[i] = f[i - 1] - f[i - 2];
while (f[(n - 1) % 6 + 1] < 0) f[(n - 1) % 6 + 1] += mod;
cout << (f[(n - 1) % 6 + 1]) % mod;
return 0;
}
矩阵快速幂
构造矩阵然后用矩阵快速幂求解。
构造矩阵:
\[\left(\begin{matrix}
f_i \\
f_{i-1}
\end{matrix}\right)
=
\left(\begin{matrix}
1 & -1 \\
1 & 0
\end{matrix}\right)
\times
\left(\begin{matrix}
f_{i-1} \\
f_{i-2}
\end{matrix}\right)
\]
所以:
\[\left(\begin{matrix}
f_n \\
f_{n-1}
\end{matrix}\right)
=
\left(\begin{matrix}
1 & -1 \\
1 & 0
\end{matrix}\right)^{n-2}
\times
\left(\begin{matrix}
f_2 \\
f_1
\end{matrix}\right)
\]
几个注意点:
- 数据比较大,要开long long;
- 快速幂里用\(n-1\)是因为\(n\)可能为\(1\),如果是\(n-2\)的话会变成负数,使快速幂无法跳出循环;
- 结果可能为负数,取余时要加\(1e9+7\)直至大于\(0\)(加一次可能不够)。
#include <iostream>
#include <cstring>
using namespace std;
const int mod = 1e9 + 7;
struct Matrix { // 矩阵
int row, col;
long long num[2][2];
};
Matrix multiply(Matrix a, Matrix b) { // 矩阵乘法
Matrix temp;
temp.row = a.row, temp.col = b.col;
memset(temp.num, 0, sizeof(temp.num));
for (int i = 0; i < a.row; ++i)
for (int j = 0; j < b.col; ++j)
for (int k = 0; k < a.col; ++k)
temp.num[i][j] = (temp.num[i][j] + a.num[i][k] * b.num[k][j] % mod) % mod;
return temp;
}
Matrix fastPow(Matrix base, long long k) { // 矩阵快速幂
Matrix ans;
ans.row = ans.col = 2;
ans.num[0][0] = ans.num[1][1] = 1;
ans.num[0][1] = ans.num[1][0] = 0;
while (k) {
if (k & 1) ans = multiply(ans, base);
base = multiply(base, base);
k >>= 1;
}
return ans;
}
int main() {
long long x, y, n;
cin >> x >> y >> n;
Matrix base;
base.row = base.col = 2;
base.num[0][0] = base.num[1][0] = 1;
base.num[0][1] = -1;
base.num[1][1] = 0;
Matrix ans = fastPow(base, n - 1);
cout << ((ans.num[1][0] * y + ans.num[1][1] * x) % mod + mod) % mod << endl;
return 0;
}