Data Structures & AlgorithmsHardCodeforces Div2 D · graph connectivity

Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and testing connectivity.

Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and testing connectivity.
def connected(n, edges):
    p = list(range(n))
    def f(x):
        while p[x] != x:
            x = p[x]
        return x
    for u, v in edges:
        p[f(u)] = f(v)
    return len({f(i) for i in range(n)}) == 1
E = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4)]
print(sum(1 for i in range(len(E)) if not connected(5, E[:i] + E[i + 1:])))
What is printed?
  1. A. 2
  2. B. 1
  3. C. 3
  4. D. 4

Correct answer: A. 2

Deleting (2,3) or (3,4) disconnects the graph, while the triangle edges are not bridges. A bridge is an edge whose removal increases the number of components.

More Coding Interview Problems questions

Exams that ask this topic