题意:
给定公式如题;求 f[n] ,n < 1e9
思路:
根据前面部分,明显的是矩阵快速幂,但是后面还加了个 P/n 向下取整
然后我们会发现 P/n 这个数对于某些n是一样的,所以我们想到有这个值进行分块处理;
只要把前 1e6 个 f 数组求出来 ,这样对于 k = P/n ,最大到1000,只要枚举k,然后此时对应k的一个区间可以用矩阵快速幂求解
注意n可能大于P;
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <cmath>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
const ll maxn = 1e6 + 7;
const ll mod = 1e9+7;
ll f[maxn];
ll A , B, C, D, P, n;
void init(ll m) {
for(ll i = 3; i < m; ++i) {
ll t = floor(P/i);
f[i] = (C*f[i-2]%mod + D*f[i-1]%mod + t)%mod;
}
}
mat mul(mat &A, mat &B) {
mat C(A.size(), vec(B[0].size()));
for(int i = 0; i < A.size(); ++i) {
for(int k = 0; k < B.size(); ++k) {
for(int j = 0; j < B[0].size(); ++j) {
C[i][j] = (C[i][j] + A[i][k]*B[k][j]%mod) % mod;
}
}
}
return C;
}
mat pow_(mat A, ll n) {
mat B(A.size(), vec(A.size()));
for(int i = 0; i < A.size(); ++i) B[i][i] = 1LL;
while(n>0) {
if(n&1) B = mul(B,A);
A = mul(A,A);
n >>= 1;
}
return B;
}
int main() {
int T; scanf("%d", &T);
while(T--) {
scanf("%lld%lld%lld%lld%lld%lld", &A, &B, &C, &D, &P, &n);
f[1] = A; f[2] = B;
if(n < maxn) {
init(n+1);
printf("%lld\n", f[n]);
continue;
}
else {
init(maxn);
mat A(1,vec(3));
mat B(3,vec(3));
int k = floor(P/maxn), m = floor(P/n);
ll l_, r_, f1, f2;
f1 = f[maxn-2], f2 = f[maxn-1];
for( k ; k >= 1; --k) {
l_ = floor(P/(k+1))+1, r_ = floor(P/k);
if(r_ < l_) continue;
if(n <= r_) {
A[0][0] = f2, A[0][1] = f1, A[0][2] = k;
B[0][0] = D, B[0][1] = 1, B[0][2] = 0;
B[1][0] = C, B[1][1] = 0, B[1][2] = 0;
B[2][0] = 1, B[2][1] = 0, B[2][2] = 1;
B = pow_(B, n-max(l_,maxn)+1);
A = mul(A,B);
printf("%lld\n", A[0][0]);
break;
}
else {
A[0][0] = f2, A[0][1] = f1, A[0][2] = k;
B[0][0] = D, B[0][1] = 1, B[0][2] = 0;
B[1][0] = C, B[1][1] = 0, B[1][2] = 0;
B[2][0] = 1, B[2][1] = 0, B[2][2] = 1;
B = pow_(B, r_-max(l_,maxn)+1);
A = mul(A,B);
f1 = A[0][1]; f2 = A[0][0];
}
}
if(m == 0) {
A[0][0] = f2, A[0][1] = f1, A[0][2] = 0;
B[0][0] = D, B[0][1] = 1, B[0][2] = 0;
B[1][0] = C, B[1][1] = 0, B[1][2] = 0;
B[2][0] = 1, B[2][1] = 0, B[2][2] = 1;
B = pow_(B, n-r_);
A = mul(A,B);
printf("%lld\n", A[0][0]);
}
}
}
return 0;
}