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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_ELVES 10
#define arrlen(x) (sizeof(x) / sizeof(x[0]))
long
checkmax(long * maxcals, long * maxelfs, int n, int cal, int elf)
{
long i, j;
for (i = 0; i < n; ++i) {
if (cal > maxcals[i]) {
if ((j = i + 1) < n) {
memmove(maxcals + j, maxcals + i, (n - j) * sizeof(long));
memmove(maxelfs + j, maxelfs + i, (n - j) * sizeof(long));
}
maxcals[i] = cal;
maxelfs[i] = elf;
break;
}
}
return i;
}
int
main(int argc, char ** argv)
{
char buf[BUFSIZ];
int elves = 1, i;
long cal = 0, maxcal[MAX_ELVES] = {0}, elf = 0, maxelf[MAX_ELVES] = {0};
while ((i = getopt(argc, argv, "p:n:")) != -1) {
switch (i) {
case 'p':
switch (atoi(optarg)) {
case 1:
elves = 1;
break;
case 2:
elves = 3;
break;
default:
fprintf(stderr, "Unexpected puzzle part %s\n", optarg);
return -1;
}
break;
case 'n':
elves = atoi(optarg);
if (elves < 1 || elves > MAX_ELVES) {
fprintf(stderr, "Unexpected number of elves %s\n", optarg);
return -1;
}
break;
default:
return -1;
}
}
while (fgets(buf, sizeof(buf), stdin)) {
char * pbuf = buf;
long n;
if ((n = strtol(buf, &pbuf, 10)) == 0 && pbuf == buf) {
checkmax(maxcal, maxelf, elves, cal, elf);
cal = 0;
++elf;
}
else {
cal += n;
}
}
checkmax(maxcal, maxelf, elves, cal, elf);
for (i = 0, cal = 0; i < elves; ++i)
cal += maxcal[i];
printf("maxcal: %ld\n", cal);
return 0;
}
|