      MODULE graphMod
      implicit none
! 重みなしのグラフを扱うためのモジュール
! 重み付きは接頭辞Wをつける．別ファイルに作る．
! 双方向，単方向の使い分けはメインプログラムで．

      integer(16),parameter,private :: prec = 8
      
      type :: nodes
        integer(prec),allocatable :: next(:)
        integer(prec) :: degree = 0
        contains
        procedure,public,pass :: appendNode
      end type
      
      contains
      subroutine appendNode( node, nodeNumber )
        implicit none
        class(nodes),intent(inout) :: node
        integer(prec),intent(in)   :: nodeNumber
        integer(prec),allocatable  :: buffer(:)
        
        if(.not.(allocated(node%next)))then
          allocate(node%next(1))
          node%degree = 0
        end if
        
        if( node%degree==0 )then
          node%next(1) = nodeNumber
          node%degree = 1
          return
        end if
        
        node%degree = node%degree + 1
        buffer = node%next(1:node%degree-1)
        if( size(node%next)<node%degree )then
          deallocate( node%next )
          allocate( node%next(node%degree*2) )
        end if
        node%next(1:node%degree) = [buffer(1:node%degree-1), nodeNumber]
        deallocate( buffer )
      end subroutine appendNode
      
      END MODULE graphMod
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      PROGRAM connectCites
      use graphMod
      IMPLICIT NONE
      INTEGER,PARAMETER :: p = 8
      integer(p) :: n,m, i,a,b
      type(nodes),allocatable :: city(:)
      integer(p),allocatable :: visited(:),ans(:)
      
      
      read*,n,m
      allocate( city(n),visited(n),ans(n) )
      do i = 1,m
        read*,a,b
        call city(a)%appendNode(b)
        call city(b)%appendNode(a)
      end do
      
      
      visited = 0
      
      do i = 1,n
        if( visited(i)/=0 ) cycle
        
     !   print*,i,'piyo'
        
        visited(i) = i
        call goNext( city(i) )
      end do
      
      ans = 0
      do i = 1,n
        ans(visited(i)) = 1
      end do
      
      
      print*,sum(ans)-1
      
      stop
      !debugg
      
      print*,'visited'
      print*,visited
      
      do i = 1,n
        print*,city(i)%next
      end do
      
      contains
      recursive subroutine goNext( now )
        implicit none
        type(nodes),intent(in) :: now
        integer(p) :: k
        
        do k = 1,now%degree
          if( visited(now%next(k))/=0 ) cycle
          
          visited(now%next(k)) = i
          call goNext( city(now%next(k)) )
        end do
      end subroutine
      
      
      END PROGRAM