N,M = map(int,input().split()) G = [[] for _ in range(N)] rG = [[] for _ in range(N)] for _ in range(M): u,v = map(int,input().split()) u -= 1 v -= 1 G[u].append(v) rG[v].append(u) def scc(N,G,rG): order = [] used = [0] * N group = [None] * N def dfs(s): used[s] = 1 for v in G[s]: if not used[v]: dfs(v) order.append(s) def rdfs(s,col): group[s] = col used[s] = 1 for v in rG[s]: if not used[v]: rdfs(v,col) for i in range(N): if not used[i]: dfs(i) used = [0] * N label = 0 for s in reversed(order): if not used[s]: rdfs(s,label) label += 1 return label,group def construct(N,G,label,group): G0 = [set() for _ in range(label)] GP = [[] for _ in range(label)] for v in range(N): lbs = group[v] for w in G[v]: lbt = group[v] if lbs == lbt: continue G0[lbs].add(lbt) GP[lbs].append(v) return G0,GP label,group = scc(N,G,rG) G0,GP = construct(N,G,label,group) ans = label - 1 for i in GP: ans += len(i) print(ans)