题意 :
f(n) = a * f(n-1) + b * f(n-3) + c, if(n > 2)
= 0, if(n ≤ 2)
(n <= 10^8)
思路 : 一开始是寻找循环节去做的, wa了几发后觉得有问题,因为它形成循环的条件需要的是连续出现一段f[x], f[x+1], f[x+2]都和前面某一段相同, 因而出现循环的可能不大。
正解应该是构造矩阵来做, 利用矩阵的幂运算二进制化来优化n。
构造出来的矩阵为 :
#include
#include
const int mod = 10007;
struct mat{
int a[5][5];
};
int n, a, b, c;
mat mul(mat a, mat b){
mat ans;
for (int i = 1; i <= 4; i++){
for (int j = 1; j <= 4; j++){
ans.a[i][j] = 0;
for (int k = 1; k <= 4; k++){
ans.a[i][j] += a.a[i][k] * b.a[k][j];
ans.a[i][j] %= mod;
}
}
}
return ans;
}
void init(mat &t){
for (int i = 1; i <= 4; i++)
for (int j = 1; j <= 4; j++)
t.a[i][j] = 0;
}
int solve(){
if (n <= 2)return 0;
mat ans, aa;
init(ans); init(aa);
aa.a[1][1] = a; aa.a[1][3] = b; aa.a[1][4] = c;
aa.a[2][1] = 1; aa.a[3][2] = 1; aa.a[4][4] = 1;
ans.a[1][1] = ans.a[2][2] = ans.a[3][3] = ans.a[4][4] = 1;
n -= 2;
while (n){
if (n & 1){
ans = mul(ans, aa);
}
n /= 2;
aa = mul(aa, aa);
}
return ans.a[1][4];
}
int main(){
int T;
scanf("%d", &T);
for (int cas = 1; cas <= T; cas++){
scanf("%d%d%d%d", &n, &a, &b, &c);
printf("Case %d: %d\n", cas, solve());
}
return 0;
}