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

using namespace std;

typedef unsigned long long ull;

ull count(ull h, ull w, vector<ull> &sizes);

int main() {
    ios_base::sync_with_stdio(false);

    ull h, w;
    int n;

    cin >> h >> w;
    cin >> n;

    ull a;
    vector<ull> sizes;
    for (int i = 0; i < n; i++) {
        cin >> a;
        sizes.push_back(a);
    }

    if (h % sizes[0] != 0 || w % sizes[0] != 0) {
        cout << -1 << endl;
    } else {
        cout << count(h, w, sizes) << endl;
    }

    return 0;
}

ull count(ull h, ull w, vector<ull> &sizes) {
    if (h == 0 || w == 0) {
        return 0;
    }

    ull a = min(w, h);
    for (ull &size: std::ranges::reverse_view(sizes)) {
        if (size <= a) {
            return (h / size) * (w / size) +
                   count(h % size, w - w % size, sizes) +
                   count(w % size, h - h % size, sizes) +
                   count(w % size, h % size, sizes);
        }
    }

    throw std::logic_error("should never happen");
}