1
0
Fork 0

07: Solve in C

This commit is contained in:
Mia Herkt 2022-12-07 19:03:14 +01:00
parent f94c3eb3cb
commit e1d55dda2e
Signed by: mia
GPG Key ID: 72E154B8622EC191
2 changed files with 1170 additions and 0 deletions

1082
07/input Normal file

File diff suppressed because it is too large Load Diff

88
07/solution.c Normal file
View File

@ -0,0 +1,88 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct entry {
char *name;
int isdir;
size_t size;
struct entry **entries;
size_t n_entries;
struct entry *parent;
} entry;
entry *findent(entry *e, int isdir, const char *name) {
for (size_t i = 0; i < e->n_entries; i++) {
if (e->entries[i]->isdir == isdir)
if (!strcmp(e->entries[i]->name, name))
return e->entries[i];
}
return NULL;
}
entry *addent(entry *parent, int isdir, const char *name) {
if (parent->n_entries)
parent->entries = realloc(parent->entries, ++(parent->n_entries) * sizeof(entry*));
else
parent->entries = malloc(++(parent->n_entries) * sizeof(entry*));
entry *e = parent->entries[parent->n_entries - 1] = calloc(1, sizeof(entry));
e->isdir = isdir;
e->name = malloc(strlen(name) + 1);
strcpy(e->name, name);
e->parent = parent;
return e;
}
int main(void) {
char l[64];
entry *root = calloc(1, sizeof(entry));
root->isdir++;
entry *current;
size_t S = 0, G = 0, required = 0;
while (fgets(l, 64, stdin)) {
l[strlen(l) - 1] = '\0';
if (l[0] == '$') {
if (l[2] == 'c')
if (l[5] == '/')
current = root;
else if (l[5] == '.')
current = current->parent;
else
current = findent(current, 1, l + 5);
} else if (l[0] == 'd') {
if (!findent(current, 1, l + 4))
addent(current, 1, l + 4);
} else {
char *p;
size_t sz = strtoul(l, &p, 10);
entry *f = addent(current, 0, p + 1);
f->size = sz;
for (f = current; f->parent; f = f->parent)
f->size += sz;
f->size += sz;
}
}
current = root;
required = 30000000UL - (70000000UL - root->size);
do {
if (current->n_entries) {
current->n_entries--;
current = (current->entries++)[0];
} else {
if (current->isdir)
if (current->size < 100000)
S += current->size;
else if (current->size >= required && (current->size < G || !G))
G = current->size;
current = current->parent;
}
} while (current);
printf("Silver: %lu\nGold: %lu\n", S, G);
}