-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh1579 v1 Daily Boolean Heap.py
66 lines (53 loc) · 1.91 KB
/
h1579 v1 Daily Boolean Heap.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
class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
totalEdges = len(edges)
bothEdges = 0
aliceEdges = 0
bobEdges = 0
both = defaultdict(set)
alice = defaultdict(set)
bob = defaultdict(set)
for tp, a, b in edges :
match tp :
case 1 :
# These ifs avoid duplicates
aliceEdges += 1
alice[a].add(b)
alice[b].add(a)
case 2 :
bobEdges += 1
bob[a].add(b)
bob[b].add(a)
case 3 :
if a not in both or b not in both:
bothEdges += 1
both[a].add(b)
both[b].add(a)
if min(aliceEdges, bobEdges) + bothEdges < n - 1 :
return -1
def helper(both: dict, person: dict) -> Set[int] :
visited = set()
toVisit = [(True, 1)] # heap [isPerson, node]
while toVisit :
tp, node = heapq.heappop(toVisit)
if node in visited :
continue
visited.add(node)
if not tp :
self.randafksf += 1
for i in both[node] :
heapq.heappush(toVisit, (False, i))
for i in person[node] :
heapq.heappush(toVisit, (True, i))
return visited
self.randafksf = 0
outputAlice = helper(both, alice)
if len(outputAlice) != n :
return -1
outputBob = helper(both, bob)
if len(outputBob) != n :
return -1
# Note: |Edges| = |Nodes| - 1 in an MST
edgesNeeded = 2 * n - 2
edgesNeeded -= self.randafksf // 2
return totalEdges - edgesNeeded