Advertisement
quetzelcoatlus

8.c

Dec 8th, 2022 (edited)
994
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.  
  6. void main(){
  7.     char *line = NULL;
  8.     size_t len = 0;
  9.     ssize_t nread;
  10.  
  11.     int sum=0,n,first=1;
  12.     char *front,*back,*p,*seen,max;
  13.     char **pots;
  14.  
  15.     while ((nread = getline(&line, &len, stdin)) != -1) {
  16.         //printf("%s",line);
  17.         if(first == 1){
  18.             n=nread-1;
  19.             front=malloc(sizeof(char)*n);
  20.             back=malloc(sizeof(char)*n);
  21.             pots=malloc(sizeof(char*)*n);
  22.             p=calloc(sizeof(char),n);
  23.             for(int i=0;i<n;i++){
  24.                 front[i]=-1;
  25.                 back[i]=-1;
  26.                 pots[i]=malloc(sizeof(char)*10);
  27.             }
  28.             first=0;
  29.         }
  30.         seen=calloc(sizeof(char),n);
  31.  
  32.         //left
  33.         max=-1;
  34.         for(int i=0; i<n; i++){
  35.             if(line[i]>max){
  36.                 sum++;
  37.                 seen[i]=1;
  38.                 max=line[i];
  39.             }
  40.         }
  41.         //printf("1 -> %d\n",sum);
  42.  
  43.         //right
  44.         max=-1;
  45.         for(int i=n-1;i>0;i--){
  46.             if(line[i] > max){
  47.                 max=line[i];
  48.                 if(!seen[i]){
  49.                     sum++;
  50.                     seen[i]=1;
  51.                 }
  52.             }
  53.         }
  54.         //printf("2 -> %d\n",sum);
  55.         for(int i=0; i<n; i++){
  56.             //up
  57.             if(line[i] > front[i]){
  58.                 front[i] = line[i];
  59.                 if(!seen[i]){
  60.                     sum++;
  61.                     seen[i]=1;
  62.                 }
  63.             }
  64.  
  65.             //down
  66.             if(line[i] < back[i]){
  67.                 if(!seen[i])
  68.                     pots[i][(int)(p[i])++]=line[i];
  69.             } else {
  70.                 while(p[i]>0 && line[i] >= pots[i][(int)p[i]-1])
  71.                     (p[i])--;
  72.                 if(!seen[i])
  73.                     pots[i][(int)(p[i])++]=line[i];
  74.             }
  75.             back[i]=line[i];
  76.         }
  77.         //printf("3 -> %d\n",sum);
  78.         free(seen);
  79.     }
  80.     for(int i=0;i<n;i++){
  81.         //printf("4-> [%d] -> %d\n",i,p[i]);
  82.         free(pots[i]);
  83.         sum += p[i];
  84.     }
  85.  
  86.     printf("%d\n",sum);
  87.  
  88.     free(front);
  89.     free(back);
  90.     free(pots);
  91.  
  92.     free(line);
  93. }
Tags: adventofcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement