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
#include <iostream>
#include <algorithm>
#include <iterator>
#include <unordered_set>

using namespace std;

int main() {
    long n, m;
    cin >> n >> m;

    long mod = 1000000007;

    if (n == 1) {
        std::cout << 0 << std::endl;
        return 0;
    }
    if (n == 2) {
        std::cout << m << std::endl;
        return 0;
    }
    if (n == 3) {
        std::cout << (m * m) % mod << std::endl;
        return 0;
    }
    int i;
    long arr[n + 1];
    for (i = 0; i <= n; i++) {
        arr[i] = 0;
    }

    arr[2] = m;
    arr[3] = (m * m) % mod;
    for (i = 4; i <= n; i++) {
        arr[i] = (((arr[i - 1] * m) % mod) + ((arr[i - 2] * (m - 1)) % mod)) % mod;
    }
    std::cout << arr[n] << std::endl;
    return 0;
}