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 <functional>
#include <algorithm>

int main() {
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    std::cin.tie(0);

    long long H, W;
    std::cin >> H >> W;

    int N;
    std::cin >> N;

    std::vector<long long> d(N);
    for(auto& x : d) {
        std::cin >> x;
    }

    if(H % d[0] != 0 || W % d[0] != 0) {
        std::cout << -1 << '\n';
        return 0;
    }

    std::function<long long(long long, long long)> calc_result = [&](long long h, long long w) -> long long {
        if(std::min(h, w) <= 0) {
            return 0L;
        }

        long long D = d[0];
        for(int x : d) {
            if(x <= std::min(h, w)) {
                D = x;
            }
        }

        long long result = 0, cnt_h = h / D, cnt_w = w / D;
        result += cnt_h * cnt_w;

        result += calc_result(h - cnt_h * D, cnt_w * D);
        result += calc_result(cnt_h * D, w - cnt_w * D);
        result += calc_result(h - cnt_h * D, w - cnt_w * D);

        return result;
    };

    std::cout << calc_result(H, W) << '\n';

    return 0;
}