题目链接:UVA 10689 Yet another Number Sequence
题目大意:
将斐波那契数列的(f_0)和(f_1)改为(a)和(b),求(f_n)的后(m)位。
题解:
很典型的一道矩阵快速幂的题目。
构造矩阵:
[left(egin{matrix}
f_i \
f_{i-1}
end{matrix}
ight)
=
left(egin{matrix}
1 & 1 \
1 & 0
end{matrix}
ight)
imes
left(egin{matrix}
f_{i-1} \
f_{i-2}
end{matrix}
ight)
]
所以:
[left(egin{matrix}
f_n \
f_{n-1}
end{matrix}
ight)
=
left(egin{matrix}
1 & 1 \
1 & 0
end{matrix}
ight)^{n-1}
imes
left(egin{matrix}
b \
a
end{matrix}
ight)
]
取后(m)位则直接在矩阵快速幂的过程中对(10^m)取余就行了。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define ll long long
const int mod[] = {0, 10, 100, 1000, 10000};
struct Matrix { // 矩阵
int row, col;
ll num[2][2];
};
Matrix multiply(Matrix a, Matrix b, int mod) { // 矩阵乘法
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;
return temp;
}
Matrix MatrixFastPow(Matrix base, ll k, int mod) { // 矩阵快速幂
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, mod);
base = multiply(base, base, mod);
k >>= 1;
}
return ans;
}
int main() {
ll a, b, n, m, t;
cin >> t;
Matrix base;
base.row = base.col = 2;
base.num[0][0] = base.num[0][1] = base.num[1][0] = 1;
base.num[1][1] = 0;
while (t--) {
cin >> a >> b >> n >> m;
Matrix ans = MatrixFastPow(base, n - 1, mod[m]);
cout << (ans.num[0][0] * b + ans.num[0][1] * a) % mod[m] << endl;
}
return 0;
}