8 void debug(const char *fmt
, ...) {
10 if (getenv("DEBUG")) {
12 vfprintf(stderr
, fmt
, ap
);
17 typedef struct node node
;
29 void process(FILE *f
, node
*n
) {
33 if (fscanf(f
, "%hhd %hhd ", &n
->n_children
, &n
->n_data
) != 2) {
34 fprintf(stderr
, "unexpected input\n");
37 if (!(n
->children
= malloc(n
->n_children
* sizeof(node
))) ||
38 !(n
->data
= malloc(n
->n_data
))) {
42 for (i
= 0; i
< n
->n_children
; i
++)
43 process(f
, &n
->children
[i
]);
44 for (i
= 0; i
< n
->n_data
; i
++) {
45 if (fscanf(f
, "%hhd ", &n
->data
[i
]) != 1) {
46 fprintf(stderr
, "unexpected input\n");
51 if (n
->data
[i
] - 1U < n
->n_children
)
52 n
->value
+= n
->children
[n
->data
[i
] - 1].value
;
54 n
->value
+= n
->data
[i
];
58 int main(int argc
, char **argv
) {
60 if (!(stdin
= freopen(argv
[1], "r", stdin
))) {
65 process(stdin
, &head
);
66 printf("read %d nodes, metadata sum %d\n", count
, sum
);
67 printf("root value %d\n", head
.value
);