forked from Adam-Jimenez/binarysearch-editorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountry Roads.py
More file actions
27 lines (26 loc) · 922 Bytes
/
Country Roads.py
File metadata and controls
27 lines (26 loc) · 922 Bytes
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
"""
Country Roads
Graph coloring solution. If we visualize our tree as rows of cities, we alternate between rows of town and rows of cities starting from the root. We chose the max out of the two possibilities.
"""
from collections import defaultdict
class Solution:
def solve(self, source, dest, population):
adj_list=defaultdict(list)
color_cities=defaultdict(list)
nodes=set()
ends=set()
for s,e in zip(source,dest):
nodes.add(s)
nodes.add(e)
ends.add(e)
adj_list[s].append(e)
color=False
start = (nodes-ends).pop()
q=[start]
while q:
for _ in range(len(q)):
cur=q.pop(0)
color_cities[color].append(population[cur])
for n in adj_list[cur]: q.append(n)
color^=True
return max(sum(x) for x in color_cities.values())