n,m = gets.chomp.split(" ").map(&:to_i);

class UnionFind
  def initialize(size)
    @rank = Array.new(size, 0)
    @parent = Array.new(size, &:itself)
    #@開始はインスタンス変数：オブジェクトが存在する間有効
  end 
 
  def unite(id_x, id_y)
    x_parent = get_parent(id_x)
    y_parent = get_parent(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_parent] += 1 if @rank[x_parent] == @rank[y_parent]
    end 
  end 
 
  def get_parent(id_x)
    @parent[id_x] == id_x ? id_x : (@parent[id_x] = get_parent(@parent[id_x]))
    # 3項演算子（xx ? yy : zz　の意味は　if xx then yy else zz end ）
    end 
 
  def same_parent?(id_x, id_y)
    get_parent(id_x) == get_parent(id_y)
  end 
 
  def count_parent
    rtn = 0 
    @parent.each_with_index do |p, index|
      rtn += 1 if p == index
    end 
    rtn 
  end 
end
 
union = UnionFind.new n
 
# クエリの回数だけ、入力受け取りを回す
m.times do
  a, b = gets.split.map{|x| x.to_i}
  union.unite(a, b)
end
 
puts union.count_parent - 1 