Problem:
Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).

Solution in Ruby (2.7.1) (judge verdict: Accepted)

class UnionFind
    def initialize(n) # 必要な配列を設定、nはノード(頂点)の数
        @rank = Array.new(n,0) # 端っこからたどって何番目の階層かを記録、大きいほうが親となる
        @parent = Array.new(n,&:itself) #初期設定では自分の親は自分の番号と同じ
    end
    def get_parent(id_x) # 根(親)を表示する関数
        @parent[id_x] = get_parent(@parent[id_x]) if id_x != @parent[id_x]
        return @parent[id_x]
    end
    def same_parent?(id_x, id_y) # ２つのノードid_x、id_yが連結しているかどうかを調べる
        get_parent(id_x) == get_parent(id_y)
        # if same_parent?(x,y)のように使う、同じ親ならtrue、別であればfalse
    end
    def unite(id_x, id_y) # ２つのノードid_x、id_yをつなげる
        x_parent = get_parent(id_x) # id_xの親
        y_parent = get_parent(id_y) # id_yの親
        return if x_parent == y_parent # この場合はすでにつながっているので何もしない,この操作をを終える
        if @rank[x_parent] > @rank[y_parent] # それぞれの親のうちより頂点に近い方にもう一方を付け加える
          @parent[y_parent] = x_parent
        else
          @parent[x_parent] = y_parent # rankが同じ場合も含めてyが大親になっている
          @rank[y_parent] += 1 if @rank[x_parent] == @rank[y_parent]
          # rankが同じ場合は仕方なく後者を親にしてrankを一つ増やす、これで一行上の操作は正当化される
        end
    end
    def tree_size(id_x) # id_xが存在するツリーに存在するノードの数
        return @parent.count(@parent[id_x])
    end
    def group_size # 全体の独立した集合の数、すなわち互いに素な集合の個数
        return @parent.uniq.size
    end
    def look_parent # 配列@parentを表示する
        return @parent
    end
    def look_rank # 配列@rankを表示する
        return @rank
    end
end

n, m = gets.strip.split.map(&:to_i)
uf = UnionFind.new(n)
rec = Array.new(n,0)
m.times do
  a,b = gets.chomp.split.map(&:to_i)
  uf.unite(a-1,b-1)
end
n.times do |i|
  rec[uf.get_parent(i)] += 1
end
rec.delete(0)
p rec.size-1