aboutsummaryrefslogtreecommitdiff
path: root/2023/20/20a.c
diff options
context:
space:
mode:
authorSebastiano Tronto <sebastiano@tronto.net>2023-12-20 16:32:41 +0100
committerSebastiano Tronto <sebastiano@tronto.net>2023-12-20 16:32:41 +0100
commit477ed667b1a9bc7f73850f45449666a8907ecaed (patch)
tree1b867729d2f5527c98b8143f730d21cd7f39b007 /2023/20/20a.c
parent1f75d7c9ebec207c8193754792076dc66eba9713 (diff)
downloadaoc-477ed667b1a9bc7f73850f45449666a8907ecaed.tar.gz
aoc-477ed667b1a9bc7f73850f45449666a8907ecaed.zip
Added solution for 20
Diffstat (limited to '2023/20/20a.c')
-rw-r--r--2023/20/20a.c101
1 files changed, 101 insertions, 0 deletions
diff --git a/2023/20/20a.c b/2023/20/20a.c
new file mode 100644
index 0000000..99b6874
--- /dev/null
+++ b/2023/20/20a.c
@@ -0,0 +1,101 @@
1#include <inttypes.h>
2#include <stdbool.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6
7#define N 100
8#define ischar(c) (c >= 'a' && c <= 'z')
9
10typedef struct {
11 int nin, nout, in[N], out[N];
12 char name[20], outc[N][20];
13 bool isff, ison, reg[N];
14} node_t;
15
16typedef struct {
17 int i, n, node[1000];
18 bool hi[1000];
19} queue_t;
20
21char *buf, line[N][N];
22int b, n;
23int64_t hitot, lowtot;
24node_t m[N];
25
26void add(queue_t *q, int v, bool hi) {
27 q->node[q->n] = v;
28 q->hi[q->n] = hi;
29 q->n++;
30}
31
32void send(queue_t *q, int v, bool hi) {
33 for (int j = 0; j < m[v].nout; j++) {
34 add(q, m[v].out[j], hi);
35 m[m[v].out[j]].reg[v] = hi;
36 if (hi) hitot++; else lowtot++;
37 }
38}
39
40void pushbutton(void) {
41 queue_t q = {0};
42
43 add(&q, b, false);
44 lowtot++;
45 while (q.i < q.n) {
46 int v = q.node[q.i];
47 bool hi = q.hi[q.i];
48 q.i++;
49
50 if (v == b) {
51 send(&q, v, hi);
52 } else if (m[v].isff) {
53 if (!hi)
54 send(&q, v, m[v].ison = !m[v].ison);
55 } else {
56 bool allhi = true;
57 for (int j = 0; j < m[v].nin; j++)
58 allhi = allhi && m[v].reg[m[v].in[j]];
59 send(&q, v, !allhi);
60 }
61 }
62}
63
64int main() {
65 for (n = 0; (buf = fgets(line[n], N, stdin)) != NULL; n++) {
66 if (ischar(*buf)) b = n;
67 m[n].isff = *buf == '%';
68 if (!ischar(*buf)) buf++;
69 for (int i = 0; ischar(*buf); m[n].name[i++] = *(buf++)) ;
70 buf += 4;
71 for (int i = 0; *buf != '\n'; i++) {
72 while (!ischar(*buf)) buf++;
73 for (int j = 0; ischar(*buf); m[n].outc[i][j++] = *(buf++)) ;
74 }
75 }
76
77 for (int i = 0; i < n; i++) {
78 for (int j = 0; m[i].outc[j][0]; j++) {
79 bool found = false;
80 for (int k = 0; k < n; k++) {
81 if (!strcmp(m[k].name, m[i].outc[j])) {
82 m[i].out[m[i].nout++] = k;
83 m[k].in[m[k].nin++] = i;
84 found = true;
85 }
86 }
87 if (!found) {
88 m[i].out[m[i].nout++] = n;
89 m[n].in[m[n].nin++] = i;
90 n++;
91 }
92 }
93 }
94
95 for (int i = 0; i < 1000; i++)
96 pushbutton();
97
98 printf("%" PRId64 " (%" PRId64 " low, %" PRId64 " hi)\n",
99 hitot * lowtot, lowtot, hitot);
100 return 0;
101}

Generated with cgit - Back to sebastiano.tronto.net