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 def main(): n, m = map(int, sys.stdin.readline().split()) parent = list(range(n)) rank = [1] * n def find(u): while parent[u] != u: parent[u] = parent[parent[u]] # Path compression u = parent[u] return u def union(u, v): root_u = find(u) root_v = find(v) if root_u == root_v: return if rank[root_u] < rank[root_v]: parent[root_u] = root_v else: parent[root_v] = root_u if rank[root_u] == rank[root_v]: rank[root_u] += 1 for _ in range(m): s, t = map(int, sys.stdin.readline().split()) union(s, t) q = int(sys.stdin.readline()) for _ in range(q): s, t = map(int, sys.stdin.readline().split()) print("yes" if find(s) == find(t) else "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.