-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh1579 v2 Parallel Stacks.py
74 lines (60 loc) · 2.11 KB
/
h1579 v2 Parallel Stacks.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
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()
toVisitPriority = [1]
toVisitSecondary = []
while toVisitPriority or toVisitSecondary :
curr = None
fromPriority = False
if toVisitPriority :
fromPriority = True
curr = toVisitPriority.pop()
else :
curr = toVisitSecondary.pop()
if curr in visited :
continue
if fromPriority :
self.randafksf += 1
visited.add(curr)
for i in both[curr] :
toVisitPriority.append(i)
for i in person[curr] :
toVisitSecondary.append(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 - 1