Advertisement
quetzelcoatlus

07.c

Dec 7th, 2022
1,031
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct Node{
  6.     char type;
  7.     int n;
  8.     int p;
  9.     char *name;
  10. };
  11.  
  12. #define MAX_SIZE 1024
  13. #define MAX_DEPTH 256
  14. #define MAX_LENGTH 64
  15.  
  16. #define QUESTION_SIZE 100000
  17.  
  18. void main(){
  19.     char *line = NULL;
  20.     size_t len = 0;
  21.     ssize_t nread;
  22.  
  23.  
  24.     struct Node *tree = malloc(sizeof(struct Node) * MAX_SIZE);
  25.  
  26.     int i=0;
  27.     tree[i].type='d';
  28.     tree[i].n=0;
  29.     tree[i].p=-1;
  30.     tree[i].name = strdup("/");
  31.  
  32.     int p=0;
  33.     int parents[MAX_DEPTH];
  34.     parents[p]=tree[i].n;
  35.  
  36.     char tmp[MAX_LENGTH];
  37.     int j,d;
  38.  
  39.     while ((nread = getline(&line, &len, stdin)) != -1) {
  40.         if(strstr(line, "$ cd /") != NULL){
  41.             p=0;
  42.         } else if(strstr(line, "$ ls") != NULL){
  43.             continue;
  44.         } else if(strstr(line, "$ cd ..") != NULL){
  45.             p--;
  46.         } else if(strstr(line, "$ cd") != NULL){
  47.             sscanf(line, "$ cd %s\n", tmp);
  48.             for(j=i; j>0; j--)
  49.                 if(tree[j].type == 'd' && tree[j].p == parents[p] && !strcmp(tmp,tree[j].name))
  50.                     break;
  51.  
  52.             parents[++p] = j;
  53.         } else if (strcmp("dir", line) < 0){
  54.             sscanf(line, "dir %s\n", tmp);
  55.             tree[++i].type='d';
  56.             tree[i].n=0;
  57.             tree[i].p=parents[p];
  58.             tree[i].name=strdup(tmp);
  59.         } else if(sscanf(line, "%d %s\n",&d,tmp) == 2){
  60.             tree[++i].type='f';
  61.             tree[i].n=d;
  62.             tree[i].p=parents[p];
  63.             tree[i].name=strdup(tmp);
  64.  
  65.             int temp_parent = parents[p];
  66.             while(temp_parent != -1){
  67.                 tree[temp_parent].n+=d;
  68.                 temp_parent=tree[temp_parent].p;
  69.             }
  70.         } else {
  71.             printf("Unrecognised line: |%s|\n", line);
  72.         }
  73.     }
  74.  
  75.     int sum=0;
  76.     for(int j=0; j<=i; j++){
  77.         if (tree[j].type == 'd' && tree[j].n <= QUESTION_SIZE)
  78.            sum += tree[j].n;
  79.         //printf("id=|%d| n=|%d| t=|%c| p=|%d| name=|%s|\n",j,tree[j].n,tree[j].type,tree[j].p,tree[j].name);
  80.     }
  81.  
  82.     printf("%d\n",sum);
  83.  
  84.     for(int j=i; j>=0; j--)
  85.         free(tree[j].name);
  86.  
  87.     free(tree);
  88.     free(line);
  89. }
  90.  
  91.  
Tags: adventofcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement