adventofcode2022/day16/sol.py

79 lines
2.1 KiB
Python

G = []
for line in open("input"):
words = line.split()
valve = words[1]
rate = words[4]
edges = [x.strip(", ") for x in words[9:]]
print(rate)
rate = rate.strip(";")
rate = rate[rate.index("=")+1:]
rate = int(rate)
G.append((valve, rate, edges))
print(G)
def save():
seen = set()
with open("input.dot", "w") as f:
print("graph {", file=f)
for v, r, E in G:
if r:
print('%s [label="%s (%s)"]' % (v, v, r), file=f)
for e in E:
if (e,v) not in seen:
print("%s -- %s" % (v,e), file=f)
seen.add((v,e))
print("}", file=f)
#save()
#import astar
score = {'AA': (0, 0, [])}
# find the largest reward we can get in n steps
# then find the largest reward we can get in n+1 steps
potential = sum(r for _,r,_ in G)
minutes = 30
for _ in range(minutes):
minutes -= 1
next = {}
for v, r, E in G:
vo = v + 'o'
s = []
o = []
if vo in score:
reward, flow, open = score[vo]
o.append((reward, flow, open))
if v in score:
reward, flow, open = score[v]
# stay, don't open valve
s.append((reward, flow, open))
# stay in place, open valve
if v not in open:
reward += r*minutes
o.append((reward, flow+r, open+[v]))
# move here from somewhere else
for e in E:
if e in score:
if v in score[e][-1]:
o.append(score[e])
else:
s.append(score[e])
eo = e+'o'
if eo in score:
if v in score[eo][-1]:
o.append(score[eo])
else:
s.append(score[eo])
if s:
next[v] = max(s)
if o:
next[vo] = max(o)
score = next
print("%d minutes left" % minutes)
for v, (r, flow, open) in sorted(score.items(), key=lambda x: x[1]):
print("\t", v, r, "\t", ",".join(open))
print(max(r for r,_,_ in score.values()))