8 void debug(const char *fmt
, ...) {
10 if (getenv("DEBUG")) {
12 vfprintf(stderr
, fmt
, ap
);
22 int main(int argc
, char **argv
) {
23 size_t len
= 0, count
= 0;
32 /* Part 1 - read in lines */
34 offset
= atoi(argv
[2]);
36 workers
= atoi(argv
[3]);
38 if (!(stdin
= freopen(argv
[1], "r", stdin
))) {
43 while (getline(&line
, &len
, stdin
) >= 0) {
45 if (sscanf(line
, "Step %c must be finished before step %c can begin. ", &a
,
46 &b
) != 2 || (unsigned)(a
-'A') > 25 || (unsigned)(b
-'A') > 25) {
47 fprintf(stderr
, "bad input\n");
50 list
[a
- 'A'].state
= a
- 'A' + 1 + offset
;
51 list
[b
- 'A'].state
= b
- 'A' + 1 + offset
;
52 strchrnul(list
[b
- 'A'].wait
, '\0')[0] = a
;
54 printf("Read %zu lines\n", count
);
56 /* Part 2 - determine output */
60 for (j
= 0; j
< workers
; j
++)
62 if (!++list
[work
[j
] - 'A'].state
)
64 for (j
= 0; j
< workers
; j
++) {
67 for (i
= 0; i
< 26; i
++) {
68 if (list
[i
].state
<= 0)
72 if (list
[*p
- 'A'].state
)
78 list
[i
].state
= -list
[i
].state
;
80 debug("time %zu worker %d starting job %c\n", count
- 1, j
, i
+ 'A');
84 } while (work
[0] || work
[1] || work
[2] || work
[3] || work
[4]);
85 printf("took %zu seconds\n", count
- 1);