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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int minElementsToConstruct(int x, int n, vector<int> &elements)
{
    vector<int> dp(x + 1, INT_MAX);
    dp[0] = 0;

    for (int i = 0; i < n; ++i)
    {
        for (int j = elements[i]; j <= x; ++j)
        {
            if (dp[j - elements[i]] != INT_MAX && dp[j - elements[i]] + 1 < dp[j])
            {
                dp[j] = dp[j - elements[i]] + 1;
            }
        }
    }

    return dp[x];
}

int retConstruction(int x, int n, vector<int> &elements)
{
    int minElements = minElementsToConstruct(x, n, elements);

    if (minElements == INT_MAX)
    {
        return -1;
    }
    else
    {
        return minElements;
    }
}

vector<int> rodconst(int x, int n, vector<int> &elements)
{
    int minElements = minElementsToConstruct(x, n, elements);

    vector<int> otp;
    vector<int> count(n, 0);

    int remainingLength = x;
    for (int i = 0; i < n; i++)
    {
        while (remainingLength >= elements[i] && minElementsToConstruct(remainingLength - elements[i], n, elements) == minElements - 1)
        {
            count[i]++;
            remainingLength -= elements[i];
            minElements--;
        }
    }

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < count[i]; j++)
        {
            otp.push_back(elements[i]);
        }
    }

    return otp;
}

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

    int x, y, n, dx = 0, dy = 0, otp = 0;
    cin >> x >> y;
    if (y > x)
    {
        swap(x, y);
    }

    cin >> n;

    vector<int> elements(n);
    for (int i = 0; i < n; i++)
    {
        cin >> elements[i];
    }

    if (retConstruction(x, n, elements) != -1 && retConstruction(y, n, elements) != -1)
    {
        for (int i = 0; i < rodconst(x, n, elements).size(); i++)
        {
            otp += y / rodconst(x, n, elements)[i];
        }

        cout << otp;
    }
    else
    {
        cout << "-1";
    }


return 0;
}