summary refs log tree commit diff homepage
path: root/2020/day14.c
blob: 78f18851ff85269c7a14a80b3695e2868fb8e6e4 (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
60
61
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long ul;
struct Write {
	ul addr;
	ul val;
};
static int compar(const void *_a, const void *_b) {
	const struct Write *a = _a;
	const struct Write *b = _b;
	if (a->addr < b->addr) return -1;
	if (a->addr > b->addr) return +1;
	return 0;
}
int main(void) {
	struct Write writes[512];
	struct Write writes2[512 * (1 << 9)];
	int len = 0, len2 = 0;
	ul mask = 0, bits = 0;
	for (;;) {
		char str[37];
		int n = scanf("mask = %s\n", str);
		if (n < 0) break;
		if (n) {
			mask = 0;
			bits = 0;
			for (ul i = 35; i < 36; --i) {
				if (str[35-i] == 'X') {
					mask |= 1UL << i;
				} else if (str[35-i] == '1') {
					bits |= 1UL << i;
				}
			}
		} else {
			ul addr, val;
			n = scanf("em[%lu] = %lu\n", &addr, &val);
			if (n < 2) break;
			writes[len++] = (struct Write) { addr, (val & mask) | bits };
			addr |= bits;
			addr &= ~mask;
			for (ul m = mask; m; m = (m - 1) & mask) {
				writes2[len2++] = (struct Write) { addr | m, val };
			}
			writes2[len2++] = (struct Write) { addr, val };
		}
	}
	mergesort(writes, len, sizeof(writes[0]), compar);
	ul sum = 0;
	for (int i = 0; i < len; ++i) {
		if (i + 1 < len && writes[i+1].addr == writes[i].addr) continue;
		sum += writes[i].val;
	}
	printf("%lu\n", sum);
	mergesort(writes2, len2, sizeof(writes2[0]), compar);
	sum = 0;
	for (int i = 0; i < len2; ++i) {
		if (i + 1 < len2 && writes2[i+1].addr == writes2[i].addr) continue;
		sum += writes2[i].val;
	}
	printf("%lu\n", sum);
}