summary refs log tree commit diff homepage
path: root/2019/day06.c
blob: 2ae79fd7c9e27b3b2fc28a2785c01960e29c27a7 (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static struct Node {
	char name[4];
	size_t parent;
} tree[2048];

static size_t node(const char *name) {
	size_t i;
	for (i = 0; tree[i].name[0]; ++i) {
		if (strcmp(name, tree[i].name)) continue;
		return i;
	}
	strncpy(tree[i].name, name, sizeof(tree[i].name));
	return i;
}

static size_t ancestors(size_t i) {
	size_t n = 0;
	while (i) {
		i = tree[i].parent;
		n++;
	}
	return n;
}

int main(void) {
	node("COM");
	char parent[4], child[4];
	while (EOF != scanf("%3s)%3s\n", parent, child)) {
		tree[node(child)].parent = node(parent);
	}
	size_t orbits = 0;
	for (size_t i = 0; tree[i].name[0]; ++i) {
		orbits += ancestors(i);
	}
	printf("%zu\n", orbits);

	size_t you[2048];
	size_t ylen = 0;
	for (size_t i = node("YOU"); i; i = tree[i].parent) {
		you[ylen++] = i;
	}
	size_t san[2048];
	size_t slen = 0;
	for (size_t i = node("SAN"); i; i = tree[i].parent) {
		san[slen++] = i;
	}
	for (size_t y = 0; y < ylen; ++y) {
		for (size_t s = 0; s < slen; ++s) {
			if (you[y] == san[s]) {
				printf("%zu\n", y + s - 2);
				return 0;
			}
		}
	}
}