class UnionFind: def __init__(self, n, w=None): self.par = [-1]*n self.rank = [0]*n self.siz = [1]*n self.cnt = n self.min_node = [i for i in range(n)] self.weight = w if w else [1]*n def root(self, x): if self.par[x] == -1: return x self.par[x] = self.root(self.par[x]) return self.par[x] def issame(self, x, y): return self.root(x) == self.root(y) def unite(self, x, y): px = self.root(x) py = self.root(y) if px == py: return False if self.rank[px] < self.rank[py]: px, py = py, px self.par[py] = px if self.rank[px] == self.rank[py]: self.rank[px] += 1 self.siz[px] += self.siz[py] self.cnt -= 1 self.min_node[px] = min(self.min_node[px], self.min_node[py]) self.weight[px] += self.weight[py] return False def count(self): return self.cnt def min(self, x): return self.min_node[self.root(x)] def getweight(self, x): return self.weight[self.root(x)] def size(self, x): return self.siz[self.root(x)] from collections import defaultdict N, M = map(int, input().split()) UV = [list(map(int, input().split())) for _ in range(M)] deg = [0 for _ in range(N)] indeg = [0 for _ in range(N)] UF = UnionFind(N) for u, v in UV: u-=1 v-=1 deg[u] += 1 indeg[v] += 1 UF.unite(u, v) plus = defaultdict(int) for i in range(N): sa = indeg[i]-deg[i] r = UF.root(i) if sa>0: plus[r] += sa ans = 0 for k in plus: if plus[k]>=2: ans+=plus[k]-1 ans += len(plus)-1 print(ans)