-
Notifications
You must be signed in to change notification settings - Fork 0
/
17.py
138 lines (109 loc) · 2.37 KB
/
17.py
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
133
134
135
136
137
138
import sys
from lib import *
sys.setrecursionlimit(10000)
input = read_input(2018, 17)
lines = input.splitlines()
clay = set()
miny = 1e1337
maxy = 0
for line in lines:
a, b = line.split(", ")
a = int(a.split("=")[1])
b1, b2 = map(int, b.split("=")[1].split(".."))
for i in range(b1, b2 + 1):
if line[0] == "x":
x, y = a, i
else:
x, y = i, a
clay.add((x, y))
miny = min(y, miny)
maxy = max(y, maxy)
reachable = set()
water = set()
dp = {}
def flow(x, y):
if y > maxy:
return False
if (x, y) in clay:
return True
if (x, y) in dp:
return dp[(x, y)]
reachable.add((x, y))
if not flow(x, y + 1):
dp[(x, y)] = False
return False
add = set()
ok = True
k = x
while (k, y) not in clay:
add.add((k, y))
if not flow(k, y + 1):
ok = False
break
k -= 1
k = x
while (k, y) not in clay:
add.add((k, y))
if not flow(k, y + 1):
ok = False
break
k += 1
reachable.update(add)
if ok:
water.update(add)
dp[(x, y)] = ok
return ok
flow(500, 0)
print(sum((x, y) != (500, 0) and y in range(miny, maxy + 1) for x, y in reachable))
clay = set()
miny = 1e1337
maxy = 0
for line in lines:
a, b = line.split(", ")
a = int(a.split("=")[1])
b1, b2 = map(int, b.split("=")[1].split(".."))
for i in range(b1, b2 + 1):
if line[0] == "x":
x, y = a, i
else:
x, y = i, a
clay.add((x, y))
miny = min(y, miny)
maxy = max(y, maxy)
reachable = set()
water = set()
dp = {}
def flow(x, y):
if y > maxy:
return False
if (x, y) in clay:
return True
if (x, y) in dp:
return dp[(x, y)]
reachable.add((x, y))
if not flow(x, y + 1):
dp[(x, y)] = False
return False
add = set()
ok = True
k = x
while (k, y) not in clay:
add.add((k, y))
if not flow(k, y + 1):
ok = False
break
k -= 1
k = x
while (k, y) not in clay:
add.add((k, y))
if not flow(k, y + 1):
ok = False
break
k += 1
reachable.update(add)
if ok:
water.update(add)
dp[(x, y)] = ok
return ok
flow(500, 0)
print(len(water))