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
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int MOD = 1000000007;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ll n, m;
    cin >> n >> m;
    int K = min(m, n);

    vector<vector<ll>>Pplus(n+1, vector<ll>(K+1)); //P+[i][k]
    vector<vector<ll>>Pminus(n+1, vector<ll>(K+1)); //P-[i][k]

    //init values
    for (int k = 0; k <= K; k++)
        Pplus[0][k] = Pminus[0][k] = 0;
    for (int i = 0; i <= n; i++)
        Pplus[i][0] = Pminus[i][0] = 0;
    Pplus[0][0] = 1;

    //dynamic
    for (int i = 1; i <= n; i++) {
        for (int k = 1; k <= K; k++) {
            Pminus[i][k] = (Pminus[i - 1][k] * (m - k) + Pplus[i - 1][k - 1] * (m - k + 1)) % MOD;
            Pplus[i][k] = (Pminus[i - 1][k] * k + Pplus[i - 1][k] * k) % MOD;
        }
    }

    //get result
    ll result = 0;
    for (int k = 0; k <= K; k++)
        result += Pplus[n][k];

    cout << result % MOD << endl;

    return 0;
}