program main
    use,intrinsic :: iso_fortran_env
    implicit none
    integer(int32):: n,m,i,a,b,cnt=0
    integer(int32), allocatable:: ar(:)


    read*, n,m
    allocate(ar, source=[(i,i=1,n)])

    do i=1,m
        read*, a,b
        ar(b) = p(a)
    end do
    do i=1,n
        ar(i) = p(ar(i))
    end do

    do i=2,n
        if (ar(i-1) /= ar(i)) cnt=cnt+1
    end do
    print'(i0)', cnt
contains
recursive function p(a) result(ret)
    integer(int32):: a,ret

    if (ar(a) == a) then
        ret = a
    else
        ret = p(ar(a))
    end if
end function
end program main