Facebook Pixel

Reverse Union Find

The previous problem counted components as edges were added to a graph. This one reverses the tape: we start with a graph of n cities wired together by a list of edges and watch the graph fall apart as those edges are removed one at a time. After each removal, report how many clusters remain, where a cluster is a maximal set of cities still connected through the edges that have not yet been removed.

Input

An integer n, the number of cities labeled 1 through n, and breaks, the list of edges in the order they will be torn down. Each entry [a, b] removes the road between cities a and b.

Output

A list of integers. The ith entry is the number of clusters remaining after the ith break.

Example

Input: n = 4, breaks = [[1, 2], [2, 3], [3, 4], [1, 4], [2, 4]]
Output: [1, 1, 2, 3, 4]
Explanation:

All four cities start connected through the five edges. Removing [1, 2] still leaves a path between every pair — 1 reaches 2 via 1 → 4 → 2 — so the count stays at 1. Removing [2, 3] keeps the graph connected through edges [1, 4], [2, 4], and [3, 4]. Removing [3, 4] isolates 3 from the rest, producing two clusters: {1, 2, 4} and {3}. Removing [1, 4] splits 1 off, giving {1}, {2, 4}, and {3}. The final removal of [2, 4] leaves four singletons.

Umbristan: Cities and breaking roads

Try it yourself

Solution

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro