Write a program which reads relations in a SNS (Social Network Service), and judges that…
- User
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.
Constraints
- Input
Assistant
pythonimport sys class UnionFind: def __init__(self, size): self.parent = list(range(size)) self.rank = [0] * size def find(self, x): while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] # Path compression x = self.parent[x] return x def union(self, x, y): x_root = self.find(x) y_root = self.find(y) if x_root == y_root: return # Union by rank if self.rank[x_root] < self.rank[y_root]: self.parent[x_root] = y_root else: self.parent[y_root] = x_root if self.rank[x_root] == self.rank[y_root]: self.rank[x_root] += 1 def main(): input = sys.stdin.readline().split() n = int(input[0]) m = int(input[1]) uf = UnionFind(n) for _ in range(m): s, t = map(int, sys.stdin.readline().split()) uf.union(s, t) q = int(sys.stdin.readline()) for _ in range(q): s, t = map(int, sys.stdin.readline().split()) if uf.find(s) == uf.find(t): print("yes") else: print("no") if __name__ == "__main__": main()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.