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

long long mod(long long x, long long p) {
    x %= p;
    if (x < 0) x += p;
    return x;
}

int main() {
    std::ios::sync_with_stdio(false);

    int n, m;
    long long p;
    std::cin >> n >> m >> p;

    std::vector<std::vector<long long>> D(n, std::vector<long long>(m));

    for (int a = 0; a < m; ++a) {
        D[0][a] = mod(m - a, p);
    }
    
    std::vector<std::tuple<long long, long long, long long>> f(m); // prev, 2-prev, bias

    for (int k = 1; k < n; ++k) {
        f[m - 1] = {1, 0, 0};
        for (int a = m - 2; a >= 0; --a) {
            auto [x, y, z] = f[a + 1];
            f[a] = {mod(2 * x + y, p),
                    mod(-x, p),
                    mod(x * D[k - 1][a + 1] + z, p)
            };
        }

        long long x = D[k - 1][0];
        for (int a = 0; a < m; ++a) {
            if (a > 0) x = mod(x + D[k - 1][a] - D[k - 1][m - a], p);
            D[k][a] = mod(std::get<0>(f[a]) * x + std::get<2>(f[a]), p);
        }
    }


    long long ret = 0;
    for (int a = 0; a < m; ++a) {
        ret += D[n - 1][a];
    }

    std::cout << mod(ret, p);

    return 0;
}