【题解】UVA12470Tribonacci

题目传送门

前言

水题解

前置芝士

矩阵乘法。

分析

暴力 \(O(n)\) 是必然超时的,所以使用矩阵乘法将递推优化至 \(O(\log n)\)。

我们设数列的第 \(n\) 项为 \(f_n\),那么我们不难发现 \[ \begin{bmatrix} f_i & f_{i+1} & f_{i + 2} \end{bmatrix} \begin{bmatrix} 0 & 0 &1\\ 1 & 0 & 1\\ 0 & 1 & 1 \end{bmatrix} = \begin{bmatrix} f_{i+1} &f_{i+2} &f_{i+3} \end{bmatrix} \] 所以直接矩阵快速幂即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
#define ll long long

using namespace std;
const int mod = 1e9 + 9;

struct matrix
{
ll a[4][4];
matrix() {memset(a, 0, sizeof a);}
matrix operator*(const matrix &b) const
{
matrix c;
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 3; j++)
for (int k = 1; k <= 3; k++)
c.a[i][j] = (c.a[i][j] + a[i][k] * b.a[k][j]) % mod;
return c;
}
};

inline ll read()
{
ll x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

int main()
{
ll n = read();
while (n)
{
matrix A;
A.a[1][2] = A.a[2][3] = A.a[3][1] = A.a[3][2] = A.a[3][3] = 1;
matrix res;
res.a[1][1] = res.a[1][2] = 1;
while (n)
{
if (n & 1) res = res * A;
A = A * A;
n >>= 1;
}
printf("%lld\n", res.a[1][1]);
n = read();
}
return 0;
}