~quf/computers-are-fast-2020

computers-are-fast-2020/src/09.c -rw-r--r-- 1.7 KiB
6f56515eLukas Himbert Draw the rest of the fine owl. 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <limits.h>

bool is_sum_of_two(long long n, const long long *numbers, size_t len) {
  for (size_t i = 1; i < len; ++i) {
    for (size_t j = 0; j < i; ++j) {
      if (numbers[i] + numbers[j] == n) {
        return true;
      }
    }
  }
  return false;
}

void extrema(const long long *numbers, size_t len, long long *min, long long *max) {
  *min = LLONG_MAX;
  *max = 0;
  for (size_t i = 0; i < len; ++i) {
    if (numbers[i] < *min) {
      *min = numbers[i];
    }
    else if (numbers[i] > *max) {
      *max = numbers[i];
    }
  }
}

int main(void) {
  long long numbers[1<<10] = { 0, };
  size_t N = 0;

  /* read input */
  int ret = 0;
  while (N < sizeof numbers / sizeof *numbers && (ret = scanf("%lld\n", &numbers[N])) > 0) {
    ++N;
  }
  if (ret < 0 && !feof(stdin)) {
    fprintf(stderr, "Error: %s.\n", strerror(errno));
    return 1;
  }
  if (N < 26) {
    fprintf(stderr, "Error: input too short.\n");
    return 1;
  }

  /* part 1 */
  long long weak = 0;
  for (size_t i = 25; i < N; ++i) {
    if (!is_sum_of_two(numbers[i], numbers + (i - 25), 25)) {
      weak = numbers[i];
      break;
    }
  }
  printf("%lld\n", weak);

  /* part 2*/
  size_t i = 0;
  size_t j = 1;
  long long sum = numbers[0] + numbers[1];
  while (j < N) {
    if (sum == weak) {
      long long min, max;
      extrema(numbers + i, j - i + 1, &min, &max);
      printf("%lld\n", min + max);
      return 0;
    }
    if (j == i + 1) {
      sum += numbers[++j];
    }
    else if (sum < weak) {
      sum += numbers[++j];
    }
    else {
      sum -= numbers[i++];
    }
  }
  fprintf(stderr, "No solution.\n");
  return 1;
}