#define _USE_MATH_DEFINES #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 1000000007; // constexpr int MOD = 998244353; constexpr int DY[]{1, 0, -1, 0}, DX[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}, DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; struct StronglyConnectedComponents { std::vector id; std::vector> vertices, comp; StronglyConnectedComponents(const std::vector> &graph, bool heavy = false) : graph(graph), heavy(heavy) { n = graph.size(); rev_graph.resize(n); for (int i = 0; i < n; ++i) for (int e : graph[i]) rev_graph[e].emplace_back(i); used.assign(n, false); id.assign(n, -1); for (int i = 0; i < n; ++i) { if (!used[i]) dfs(i); } int now = 0; for (int i = n - 1; i >= 0; --i) { if (id[order[i]] == -1) { if (heavy) vertices.emplace_back(); rev_dfs(order[i], now++); } } comp.resize(now); for (int i = 0; i < n; ++i) for (int e : graph[i]) { if (id[i] != id[e]) comp[id[i]].emplace_back(id[e]); } // if (heavy) { // for (int i = 0; i < now; ++i) std::sort(vertices[i].begin(), vertices[i].end()); // } } private: bool heavy; int n; std::vector> graph, rev_graph; std::vector used; std::vector order; void dfs(int ver) { used[ver] = true; for (int e : graph[ver]) { if (!used[e]) dfs(e); } order.emplace_back(ver); } void rev_dfs(int ver, int now) { id[ver] = now; if (heavy) vertices[now].emplace_back(ver); for (int e : rev_graph[ver]) { if (id[e] == -1) rev_dfs(e, now); } } }; int main() { int n, m; cin >> n >> m; vector> graph(n); while (m--) { int a, b; cin >> a >> b; --a; --b; graph[a].emplace_back(b); } StronglyConnectedComponents scc(graph); const int x = scc.comp.size(); if (x == 1) { cout << 0 << '\n'; return 0; } vector is_root(x, true); int leaf = 0; REP(i, x) { for (int j : scc.comp[i]) is_root[j] = false; leaf += scc.comp[i].size() == 0; } cout << max(static_cast(count(ALL(is_root), true)), leaf) << '\n'; return 0; }