-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25.py
79 lines (66 loc) · 1.86 KB
/
25.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
# pylint: skip-file
# mypy: ignore-errors
# flake8: noqa
from collections import defaultdict, deque
from copy import deepcopy
input_value = open("input.txt", "r").read()
lines = input_value.split("\n")
neighbors = defaultdict(set)
edges = []
for line in lines:
[start, ends] = line.split(": ")
ends = ends.split(" ")
for end in ends:
edges.append(tuple(sorted((start, end))))
neighbors[start].add(end)
neighbors[end].add(start)
def cut_and_test(neighbors, wires):
for start, end in wires:
neighbors[start].discard(end)
neighbors[end].discard(start)
sets = []
seen = set()
for vertex in neighbors:
if vertex in seen:
continue
sets.append(set())
stack = [vertex]
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
sets[-1].add(current)
for neighbor in neighbors[current]:
stack.append(neighbor)
for start, end in wires:
neighbors[start].add(end)
neighbors[end].add(start)
return sets
def union(iterable):
initial = set()
for item_set in iterable:
initial |= item_set
return item_set
depths = []
for start, end in edges:
queue = deque((vertex, 1) for vertex in neighbors[start] - {end})
seen = set()
seen.add(start)
# print(queue)
while queue:
(current, depth) = queue.popleft()
if current == end:
depths.append((depth, (start, end)))
break
if current in seen:
continue
seen.add(current)
queue.extend((neighbor, depth + 1) for neighbor in neighbors[current])
lengths = [
len(item)
for item in cut_and_test(
neighbors, [x[1] for x in sorted(depths, reverse=True)[:3]]
)
]
print(lengths[0] * lengths[1])