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
// PA 2024 3C - Obrazy
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

long long largestPainting(long long m, long long n, vector<long long> *paintings)
{
	long long size = min(m, n);
	long long largest = -1;
	
	for (unsigned i = 0; i < paintings->size(); ++i) {
		if (size < (*paintings)[i]) {
			break;
		}
		largest = (*paintings)[i];
	}
	
	return largest;
}

long long getMinTrips(long long m, long long n, vector<long long> *paintings)
{
	if (m == 0 || n == 0) {
		return 0;
	}
	
	long long largest = largestPainting(m, n, paintings);
	if (largest == -1) {
		return -1;
	}
	
	long long a = getMinTrips(m % largest, largest, paintings);
	if (a == -1) {
		return -1;
	}
	long long b = getMinTrips(largest, n % largest, paintings);
	if (b == -1) {
		return -1;
	}
	long long c = getMinTrips(m % largest, n % largest, paintings);
	if (c == -1) {
		return -1;
	}
	
	return (n / largest) * a + (m / largest) * b + c + (m / largest) * (n / largest);
}

int main()
{
	ios_base::sync_with_stdio(0);
	long long m, n, q, a;
	vector<long long> paintings;
	
	cin >> m;
	cin >> n;
	cin >> q;
	
	for (int i = 0; i < q; ++i) {
		cin >> a;
		paintings.push_back(a);
	}
	
	cout << getMinTrips(m, n, &paintings) << endl;		
	
	return 0;
}