day 11 part 2
This commit is contained in:
parent
1b9a66f49b
commit
a071433689
13
day11/sample2
Normal file
13
day11/sample2
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
svr: aaa bbb
|
||||||
|
aaa: fft
|
||||||
|
fft: ccc
|
||||||
|
bbb: tty
|
||||||
|
tty: ccc
|
||||||
|
ccc: ddd eee
|
||||||
|
ddd: hub
|
||||||
|
hub: fff
|
||||||
|
eee: dac
|
||||||
|
dac: fff
|
||||||
|
fff: ggg hhh
|
||||||
|
ggg: out
|
||||||
|
hhh: out
|
||||||
65
day11/sol.py
65
day11/sol.py
@ -8,29 +8,66 @@ def solve(input):
|
|||||||
V.append(v)
|
V.append(v)
|
||||||
G[v] = parts
|
G[v] = parts
|
||||||
|
|
||||||
extra = [e for edges in G.values() for e in edges if e not in V]
|
sinks = [e for edges in G.values() for e in edges if e not in V]
|
||||||
V += extra
|
V += sinks
|
||||||
for v in extra:
|
for v in sinks:
|
||||||
G[v] = []
|
G[v] = []
|
||||||
|
|
||||||
|
# reversed graph
|
||||||
|
R = {}
|
||||||
|
for v, E in G.items():
|
||||||
|
for e in E:
|
||||||
|
R.setdefault(e, []).append(v)
|
||||||
|
|
||||||
Q = [(0,'you')]
|
# topological sort
|
||||||
dist = {}
|
# T is an order of vertices such that each vertex is
|
||||||
|
# listed _after_ all the vertices connected to its incoming edges.
|
||||||
|
T = []
|
||||||
|
seen = set()
|
||||||
|
def visit(v):
|
||||||
|
if v not in seen:
|
||||||
|
seen.add(v)
|
||||||
|
for e in R.get(v,()):
|
||||||
|
visit(e)
|
||||||
|
T.append(v)
|
||||||
|
|
||||||
|
visit('out')
|
||||||
|
#T.reverse()
|
||||||
|
#print(T)
|
||||||
|
|
||||||
|
def paths(start,end):
|
||||||
|
Q = [(0,start)]
|
||||||
|
seen = set()
|
||||||
paths = {v:0 for v in V}
|
paths = {v:0 for v in V}
|
||||||
paths['you'] = 1
|
paths[start] = 1
|
||||||
while Q:
|
for v in T:
|
||||||
cost, v = heapq.heappop(Q)
|
if v in seen:
|
||||||
if v in dist:
|
|
||||||
continue
|
continue
|
||||||
dist[v] = cost
|
seen.add(v)
|
||||||
for e in G[v]:
|
for e in G[v]:
|
||||||
if e not in dist:
|
|
||||||
heapq.heappush(Q, (cost+1, e))
|
|
||||||
paths[e] += paths[v]
|
paths[e] += paths[v]
|
||||||
print(paths)
|
#print(paths)
|
||||||
print(paths['out'])
|
return paths[end]
|
||||||
|
|
||||||
|
if 'you' in G:
|
||||||
|
# Part 1:
|
||||||
|
# find all paths from you -> out
|
||||||
|
print(paths('you', 'out'))
|
||||||
|
|
||||||
|
if 'svr' in G:
|
||||||
|
# Part 2: find all paths that pass through
|
||||||
|
# svr -> fft -> dac -> out, or
|
||||||
|
# svr -> dac -> fft -> out.
|
||||||
|
sf = paths('svr', 'fft')
|
||||||
|
sd = paths('svr', 'dac')
|
||||||
|
fd = paths('fft', 'dac')
|
||||||
|
df = paths('dac', 'fft')
|
||||||
|
do = paths('dac', 'out')
|
||||||
|
fo = paths('fft', 'out')
|
||||||
|
|
||||||
|
print(sf*fd*do + sd*df*fo)
|
||||||
|
|
||||||
|
|
||||||
solve("sample")
|
solve("sample")
|
||||||
|
solve("sample2")
|
||||||
solve("input")
|
solve("input")
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user