Lv.4divide-and-conquermathmatrix-exponentiation
Far Terms of a Linear Recurrence
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A sequence follows a linear recurrence of order = coef.length:
with the first terms given by init (init[i] ). For each n in queries (up to ), return modulo
, in query order.
Examples
| coef | init | queries | result |
|---|---|---|---|
[1, 1] | [0, 1] | [10, 0, 1, 50] | [55, 0, 1, 586268941] |
[2, 0, 1] | [1, 1, 1] | [3, 4, 5] | [3, 7, 15] |
[3] | [2] | [0, 1, 1000000000000000000] | [2, 6, 492673366] |
Example 1 — Fibonacci numbers; .
Example 2 — gives .
Example 3 — , even for .
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(coef: int[], init: int[], queries: long[]) → int[]
Constraints
-
coef.lengthinit.length -
coef[i],init[i] -
queries.length -
queries[q]
Expected complexity
- Time
- O(K^3 log N + Q K^2 log N)
- Space
- O(K^2 log N)
Examples
| coef | init | queries | Expected |
|---|---|---|---|
[1,1] | [0,1] | [10,0,1,50] | [55,0,1,586268941] |
[2,0,1] | [1,1,1] | [3,4,5] | [3,7,15] |
[3] | [2] | [0,1,1000000000000000000] | [2,6,492673366] |
Hint
Hint
Advancing one step multiplies the state by the companion matrix , so is the first entry of , computed by repeated squaring. With many queries, precompute once () and answer each query with matrix-vector products ( per query). A fresh matrix power per query, , exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 2794 ms | derived |
| Java 25 | 1042 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 3 | verdict only |