N, M = gets.chomp.split.map(&:to_i)

dp = []

1.upto(M) do |m|
  is_include = false
  a_m, b_m = gets.chomp.split.map(&:to_i)

  dp.each do |island|
    if island.include?(a_m) || island.include?(b_m)
      is_include = true
      island.push(a_m, b_m)
      island.uniq!
    end
  end
  if !is_include
    dp.push([a_m, b_m])
  end
end

solo_count = N - dp.flatten.uniq.count

puts dp.length + solo_count - 1