-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorders.c
114 lines (92 loc) · 2.24 KB
/
orders.c
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
106
107
108
109
110
111
112
113
114
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
// customary values
#define IMP -1
#define AMB -2
// globals
int N;
int C[104];
int M;
int S[1004];
int memo[30004];
// returns index of next item in order for total s
// ibid, but without memo
int next_item(int);
int next_item_raw(int);
int next_item(int s) {
if (memo[s] || s==0)
return memo[s];
else
return memo[s] = next_item_raw(s);
}
int next_item_raw(int s) {
assert(s>0);
// try packing in other orders
int ret = 0;
for (int i=1; i<N; i++) {
int cost = C[i];
int nxt_s = s-C[i];
// doesn't fit
if (nxt_s < 0)
break;
// fits just right
if (nxt_s == 0)
goto SOLN;
// recur
int nxt = next_item(nxt_s);
if (nxt == IMP)
continue;
if (nxt == AMB)
return AMB;
assert(nxt>0);
// permutation check; if the next pointed to
// index is less than our current one, then
// we will have already attempted an equiv. perm.
// note == to is just fine, since we allow repeats.
if (nxt < i)
continue;
SOLN: if (ret)
return AMB;
else
ret=i;
}
return ret ? ret : IMP;
}
void production() {
// menu
scanf("%d\n", &N);
N++;
for (int i=1; i<N; i++)
scanf("%d", &C[i]);
// orders
scanf("%d\n", &M);
for (int i=0; i<M; i++)
scanf("%d", &S[i]);
// GO!
for (int i=0; i<M; i++) {
int cost = S[i];
switch ( next_item(cost) ) {
case IMP:
printf("Impossible");
break;
case AMB:
printf("Ambiguous");
break;
default:
while (cost) {
int it = next_item(cost);
assert(it>0);
assert( it<=next_item(cost-C[it]) || (cost-C[it] == 0) );
printf("%d ", it);
cost -= C[it];
assert(cost>=0);
}
}
printf("\n");
}
}
int main() {
production();
return 0;
}