#C5622. Connect the Forest

    ID: 49292 Type: Default 1000ms 256MiB

Connect the Forest

Connect the Forest

You are given a forest (an undirected acyclic graph) with (n) nodes and (m) edges. A forest is a collection of trees (i.e. a disjoint union of trees). Your task is to determine the minimum number of additional edges required to connect all nodes into a single spanning tree.

In formal terms, if the forest has (C) connected components, then the minimum number of edges needed is (C - 1).

inputFormat

The input is read from stdin and contains the following:

  • The first line contains two integers \(n\) and \(m\) (\(1 \leq n \leq 10^5\); \(0 \leq m \leq n-1\)).
  • The next \(m\) lines each contain two integers \(u\) and \(v\) describing an edge between nodes \(u\) and \(v\) (\(1 \leq u, v \leq n\)).

outputFormat

Output a single integer to stdout representing the minimum number of additional edges required to connect all nodes into one connected spanning tree.## sample

6 3
1 2
2 3
4 5
2