UVa 12653 - Buses

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

長度為 n (保證為 5 的倍數)個對列,小公車長度為 5,種類有 K 種,大公車長度 10,種類有 L 種,請問排列的方法數有多少種?

Sample Input

1
2
3
4
25 5 5
5 1000 1000
20 17 31
15 9 2

Sample Output

1
2
3
4
006000
001000
111359
000765

Solution

推導公式如下

$A_{n} = K * A_{n-1} + L * A_{n-2}$

考慮塞入最後一台車的類型,找到遞迴公式。之後將其變成線性變換的結果。

$$M = \begin{bmatrix} K & 1 \\ L & 0 \end{bmatrix} \\ M^n = \begin{bmatrix} A^n & A^{n-1} \\ A^{n-1} & A^{n-2} \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
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <string.h>
const long long mod = 1000000LL;
struct Matrix {
long long v[2][2];
int row, col; // row x col
Matrix(int n, int m, long long a = 0) {
memset(v, 0, sizeof(v));
row = n, col = m;
for(int i = 0; i < row && i < col; i++)
v[i][i] = a;
}
Matrix operator*(const Matrix& x) const {
Matrix ret(row, x.col);
for(int i = 0; i < row; i++)
for(int j = 0; j < x.col; j++)
for(int k = 0; k < col; k++)
ret.v[i][j] = (ret.v[i][j] + v[i][k] * x.v[k][j]%mod)%mod;
return ret;
}
Matrix operator^(const long long& n) const {
Matrix ret(row, col, 1), x = *this;
long long y = n;
while(y) {
if(y&1) ret = ret * x;
y = y>>1, x = x * x;
}
return ret;
}
};
int main() {
long long N, K, L;
while (scanf("%lld %lld %lld", &N, &K, &L) == 3) {
N /= 5;
// long long dp[120]= {};
// dp[0] = 1;
// for (int i = 1; i <= N; i++) {
// dp[i] = dp[i-1] * K;
// if (i - 2 >= 0) {
// dp[i] += dp[i-2] * L;
// }
// }
Matrix A(2, 2, 0);
A.v[0][0] = K%mod, A.v[0][1] = 1;
A.v[1][0] = L%mod, A.v[1][1] = 0;
Matrix M = A ^ N;
printf("%06lld\n", M.v[0][0]);
}
return 0;
}
/*
$ a_{n} = K a_{n-1} + L a_{n-2} $
25 5 5
5 1000 1000
20 17 31
15 9 2
*/