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 DSU: def __init__(self, size): self.parent = list(range(size)) self.rank = [1] * size def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): x_root = self.find(x) y_root = self.find(y) if x_root == y_root: return 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 n, m = map(int, sys.stdin.readline().split()) dsu = DSU(n) for _ in range(m): s, t = map(int, sys.stdin.readline().split()) dsu.union(s, t) q = int(sys.stdin.readline()) for _ in range(q): s, t = map(int, sys.stdin.readline().split()) print("yes" if dsu.find(s) == dsu.find(t) else "no")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.