-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.go
132 lines (119 loc) · 2.47 KB
/
15.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"bufio"
"fmt"
"os"
)
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
type interval struct {
left, right int
}
func (i interval) intersect(with interval) bool {
return i.right >= with.left && i.left <= with.left ||
with.right >= i.left && with.left <= i.left
}
func (i interval) merge(with interval) interval {
if i.intersect(with) {
return interval{min(i.left, with.left), max(i.right, with.right)}
}
return i
}
func (i interval) len() int {
return i.right - i.left + 1
}
type pos struct{ x, y int }
type sensor struct {
pos pos
beacon pos
}
func (s sensor) merge(coverage []interval, targety int) []interval {
result := make([]interval, len(coverage))
copy(result, coverage)
distance := abs(s.beacon.x-s.pos.x) + abs(s.beacon.y-s.pos.y)
if abs(targety-s.pos.y) <= distance {
result = append(result, interval{
s.pos.x - (distance - abs(targety-s.pos.y)),
s.pos.x + (distance - abs(targety-s.pos.y)),
})
for {
merged := []interval{}
skip := map[int]bool{}
for i := 0; i < len(result); i++ {
if _, found := skip[i]; found {
continue
}
var intersect = false
for j := i + 1; j < len(result); j++ {
if result[i].intersect(result[j]) {
merged = append(merged, result[i].merge(result[j]))
skip[j] = true
intersect = true
}
}
if !intersect {
merged = append(merged, result[i])
}
}
if len(merged) == len(result) {
break
}
result = merged
}
}
return result
}
func beacons(sensors []sensor, target int) int {
result := map[int]bool{}
for _, b := range sensors {
if b.beacon.y == target {
result[b.beacon.x] = true
}
}
return len(result)
}
func coverage(sensors []sensor, target int) []interval {
result := []interval{}
for _, s := range sensors {
result = s.merge(result, target)
}
return result
}
func main() {
input := bufio.NewScanner(os.Stdin)
sensors := []sensor{}
for input.Scan() {
var s sensor
fmt.Sscanf(input.Text(), "Sensor at x=%d, y=%d: closest beacon is at x=%d, y=%d",
&s.pos.x, &s.pos.y, &s.beacon.x, &s.beacon.y)
sensors = append(sensors, s)
}
n1 := 0
for _, c := range coverage(sensors, 2000000) {
n1 += c.len()
}
n1 -= beacons(sensors, 2000000)
for y := 0; y <= 4000000; y++ {
c := coverage(sensors, y)
if len(c) > 1 {
fmt.Println(n1, (c[0].right+1)*4000000+y)
break
}
}
}