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
#include <iostream>
#include <vector>

int64_t pos(int32_t i, int32_t j, int64_t l) {
    return i * l + j;
}

std::vector<int64_t> mult(const std::vector<int64_t> &a, const std::vector<int64_t> &b, int64_t l, int32_t p) {
    std::vector<int64_t> out(l * l);
    for (int32_t i = 0; i < l; ++i) {
        for (int32_t j = 0; j < l; ++j) {
            for (int32_t k = 0; k < l; ++k) {
                out[pos(i, j, l)] = (a[pos(i, k, l)] * b[pos(k, j, l)] + out[pos(i, j, l)]) % p;
            }
        }
    }
    return out;
}

int main() {
    int32_t n, m, p;
    std::cin >> n >> m >> p;

    std::vector<int64_t> init(m * m * m * m);
    for (int32_t i = 0; i < m; ++i) {
        for (int32_t j = i; j < m; ++j) {
            for (int32_t i_ = 0; i_ <= j; ++i_) {
                for (int32_t j_ = std::max(i, i_); j_ < m; ++j_) {
                    init[pos(pos(i, j, m), pos(i_, j_, m), m * m)] = 1;
                }
            }
        }
    }

    std::vector<int64_t> now = init;
    std::vector<int64_t> post(m * m * m * m);
    for (int32_t i = 0; i < m * m; ++i) {
        post[pos(i, i, m * m)] = 1;
    }
    while (n > 1) {
        if (n % 2 == 0) {
            now = mult(now, now, m * m, p);
            n /= 2;
        } else {
            post = mult(now, post, m * m, p);
            now = mult(now, now, m * m, p);
            n = (n - 1) / 2;
        }
    }
    now = mult(now, post, m * m, p);

    int32_t i = pos(0, m - 1, m);
    int32_t out = 0;
    for (int64_t j = 0; j < m * m; ++j) {
        out = (now[pos(i, j, m * m)] + out) % p;
    }
    std::cout << out << "\n";
}