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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <vector>
#include <algorithm>

long long solve(long long w, long long h, const std::vector<long long> &sq, long long last_i = 0)
{
    if (w == 0 || h == 0)
    {
        return 0;
    }

    for (long long i = last_i; i < sq.size(); i++)
    {
        long long s = sq[i];
        if (w >= s && h >= s)
        {
            long long fits = (w / s) * (h / s);
            //std::clog << "fits: " << fits << " for " << s << "x" << s << std::endl;
            long long remW = w - (w / s) * s;
            long long remH = h - (h / s) * s;

            long long total = fits;

            long long sqR = remW > 0 ? solve(remW, h - remH, sq, i) : 0;
            if (sqR == -1)
                return -1;
            total += sqR;

            long long sqB = remH > 0 ? solve(w - remW, remH, sq, i) : 0;
            if (sqB == -1)
                return -1;
            total += sqB;

            if (remW > 0 && remH > 0)
            {
                long long sqC = solve(remW, remH, sq, i);
                if (sqC == -1)
                    return -1;
                total += sqC;
            }

            return total;
        }
    }

    return -1;
}

int main()
{
    long long w, h;
    std::cin >> w >> h;
    long long n;
    std::cin >> n;
    std::vector<long long> v(n);
    for (long long i = 0; i < n; i++)
    {
        std::cin >> v[i];
    }

    if (w % v.front() != 0 || h % v.front() != 0)
    {
        std::cout << "-1\n";
        return 0;
    }

    std::sort(v.begin(), v.end(), std::greater<long long>());
    long long result = solve(w, h, v);
    std::cout << result << std::endl;
    return 0;
}