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

dp = {}
dp2 = []

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

  if !dp[a_m].nil? && dp[b_m].nil?
    dp[b_m] = dp[a_m]
    dp2[dp[a_m]].push(b_m)
  elsif dp[a_m].nil? && !dp[b_m].nil?
    dp[a_m] = dp[b_m]
    dp2[dp[b_m]].push(a_m)
  elsif !dp[a_m].nil? && !dp[b_m].nil?
    if dp[a_m] > dp[b_m]
      dp2[dp[a_m]].each do |k|
        dp[k] = dp[b_m]
      end
      dp[a_m] = dp[b_m]
    else
      dp2[dp[b_m]].each do |k|
        dp[k] = dp[a_m]
      end
      dp[b_m] = dp[a_m]
    end
  else
    dp[a_m] = m
    dp[b_m] = m
    dp2[m] = [a_m, b_m]
  end
end

solo_count = N - dp.keys.uniq.length

puts dp.values.uniq.count + solo_count - 1