typedef long long ll; typedef long double ld; #include using namespace std; #define int long long // Union-Find struct UnionFind { // core member vector par; // constructor UnionFind() { } UnionFind(int n) : par(n, -1) { } void init(int n) { par.assign(n, -1); } // core methods int root(int x) { if (par[x] < 0) return x; else return par[x] = root(par[x]); } bool same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x), y = root(y); if (x == y) return false; if (par[x] > par[y]) swap(x, y); // merge technique par[x] += par[y]; par[y] = x; return true; } int size(int x) { return -par[root(x)]; } // debug friend ostream& operator << (ostream &s, UnionFind uf) { map> groups; for (int i = 0; i < uf.par.size(); ++i) { int r = uf.root(i); groups[r].push_back(i); } for (const auto &it : groups) { s << "group: "; for (auto v : it.second) s << v << " "; s << endl; } return s; } }; signed main(){ ll n,m; std::cin >> n>>m; vector nyu(n),shu(n); UnionFind uf(n); vector jiko(n); for (int i = 0; i < m; i++) { ll u,v; std::cin >> u>>v; u--;v--; uf.merge(u,v); shu[u]++; nyu[v]++; if(u==v){ jiko[u]++; } } set kan; map ma; ll cnt = 0; set uni; for (int i = 0; i < n; i++) { uni.insert(uf.root(i)); if(shu[i]-nyu[i]>0){ ma[uf.root(i)] += shu[i]-nyu[i]; } if(shu[i]==0&&nyu[i]==0)cnt++; } ll ans = 0; for (auto e : ma) { ans += e.second-1; } ans += max(0ll,(ll)uni.size()-(ll)ma.size()-cnt); std::cout << ans << std::endl; };