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
72
73
74
75
// Obrazy - 2024 Potyczki Algorytmiczne
#include <bits/stdc++.h>
using namespace std;

void print_vec(vector<pair<int,int>> v)
{
    for(int i = 0; i < v.size(); ++i)
    {   
        cerr << i << " a:" << v[i].first << " b:" << v[i].second << endl;
    }
    cerr << endl;
}

int main ()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int a,b,n;
    long long res = 0;

    cin >> a >> b;
    cin >> n;
    vector<int> obr(n);
    vector<pair<int,int>> sciany;

    for(int i = n-1; i >= 0; --i)
    {
        cin >> obr[i];
    }

    if(a%obr[n-1] or b%obr[n-1])
    {
        cout << -1;
        return 0;
    }
    sciany.push_back(make_pair(a,b));
    //print_vec(sciany);

    while(sciany.size())
    {   
        //cerr << endl;
        //print_vec(sciany);
        a = sciany.back().first;
        b = sciany.back().second;
        sciany.pop_back();

        if(a > b)
            swap(a, b);
        for(int i = 0; i < n; ++i)
        {

            if(obr[i] <= a)
            {
                int x = a/obr[i];
                int y = b/obr[i];
                res+= (long long)x*y;
                
                if(a - x*obr[i] > 0)
                {
                    sciany.push_back(make_pair(a - x*obr[i], y*obr[i]));
                }
                if(b - y*obr[i] > 0)
                {
                    sciany.push_back(make_pair(b - y*obr[i], a));
                }
                break;

            }
        }

    }
    cout << res;

    return 0;
}