Advertisement
Guest User

advent3.c

a guest
Dec 6th, 2019
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <limits.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define N 20
  7. #define MASK ((1L<<N) - 1)
  8. static struct {
  9.     short x, y, wire;
  10. } table[1L<<N];
  11.  
  12. static size_t
  13. find(int x, int y)
  14. {
  15.     unsigned long s = x*0x414caee9UL ^ y*0x6a899563UL;
  16.     size_t i = s & MASK;
  17.     for (;;) {
  18.         if (!table[i].wire) {
  19.             table[i].x = x;
  20.             table[i].y = y;
  21.             return i;
  22.         }
  23.         if (table[i].x == x && table[i].y == y) {
  24.             return i;
  25.         }
  26.         i = (s = s*0x166c5445UL + 1)>>(32 - N) & MASK;
  27.     }
  28. }
  29.  
  30. int
  31. main(void)
  32. {
  33.     int id = 1;
  34.     int x = 0, y = 0;
  35.     long max = LONG_MAX;
  36.  
  37.     char dir;
  38.     int steps;
  39.     while (scanf(" %c%d", &dir, &steps) == 2) {
  40.         static const int tx[] = {+1, +0, +0, -1};
  41.         static const int ty[] = {+0, +1, -1, +0};
  42.         int dx = tx[(dir>>2&3) + (dir&1)];
  43.         int dy = ty[(dir>>2&3) + (dir&1)];
  44.  
  45.         while (steps--) {
  46.             size_t t = find(x += dx, y += dy);
  47.             if (table[t].wire && table[t].wire != id) {
  48.                 long dist = labs(x) + labs(y);
  49.                 if (dist < max) {
  50.                     max = dist;
  51.                 }
  52.             }
  53.             table[t].wire = id;
  54.         }
  55.  
  56.         if (getchar() != ',') {
  57.             id++;
  58.             x = y = 0;
  59.         }
  60.     }
  61.  
  62.     printf("%ld\n", max);
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement