import sys input = sys.stdin.readline N,M=map(int,input().split()) E=[list(map(int,input().split())) for i in range(M)] IN=[0]*(N+1) OUT=[0]*(N+1) # UnionFind Group = [i for i in range(N+1)] # グループ分け Nodes = [1]*(N+1) # 各グループのノードの数 def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): if Nodes[find(x)] < Nodes[find(y)]: Nodes[find(y)] += Nodes[find(x)] Nodes[find(x)] = 0 Group[find(x)] = find(y) else: Nodes[find(x)] += Nodes[find(y)] Nodes[find(y)] = 0 Group[find(y)] = find(x) for a,b in E: Union(a,b) LEN=0 for i in range(1,N+1): if find(i)==i: LEN+=1 for a,b in E: IN[a]+=1 OUT[b]+=1 INP=[0]*(N+1) for i in range(1,N+1): if IN[i]>OUT[i]: INP[find(i)]+=IN[i]-OUT[i] LIST=[] for i in range(1,N+1): if find(i)==i and (IN[i]>0 or OUT[i]>0): LIST.append(INP[i]) LIST.sort(reverse=True) ANS=0 for l in LIST: ANS+=max(l-1,0) ANS+=len(LIST)-1 print(ANS)