We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def find_wire(m, q, games, wires):
# Create a union-find set
uf = UnionFind(m)
# Iterate through the wires
for wire in wires:
# Connect the two friends and merge their groups
uf.union(wire[0]-1, wire[1]-1)
# Check if the group that the friends belong to now contains all the friends
# in the same game
game = games[wire[0]-1]
if uf.find(game-1) == uf.find(game):
print(wire[0])
return
# If no group contains all the friends in the same game, print -1
print(-1)
Union-find set class
class UnionFind:
def init(self, n):
self.parent = [i for i in range(n)]
self.size = [1] * n
Jim and his LAN Party
You are viewing a single comment's thread. Return to all comments →
def find_wire(m, q, games, wires): # Create a union-find set uf = UnionFind(m)
Union-find set class
class UnionFind: def init(self, n): self.parent = [i for i in range(n)] self.size = [1] * n
Read input
m, n, q = map(int, input().split()) games = list(map(int, input().split())) wires = [tuple(map(int, input().split())) for _ in range(q)]
Find the wire
find_wire(m, q, games, wires)