Skip to content
c++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

constexpr int N=100005;

std::vector<int>g[N];
int dfn[N],low[N],timer;
int scc[N],sccCnt;
std::vector<int>stk;
bool in_stk[N];
int degin[N];

int n,m;

void tarjan(int u){
    dfn[u]=low[u]=++timer;
    stk.push_back(u);
    in_stk[u]=true;

    for(int v:g[u]){
        if(!dfn[v]){
            tarjan(v);
            low[u]=std::min(low[u],low[v]);
        }else if(in_stk[v]){
            low[u]=std::min(low[u],dfn[v]);
        }
    }

    if(dfn[u]==low[u]){
        ++sccCnt;
        int v;
        do{
            v=stk.back();
            stk.pop_back();
            in_stk[v]=false;
            scc[v]=sccCnt;
        }while(v!=u);
    }
}
void fc() {
    std::cin>>n>>m;
    std::vector<std::pair<int,int>>e(m);
    for(auto& [x,y]:e){
        std::cin>>x>>y;
        g[x].push_back(y);
    }

    for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);


    int cnt=sccCnt;
    for(auto& [x,y]:e){
        int u=scc[x],v=scc[y];
        if(u==v)continue;
        if(degin[v]++==0)cnt--;
    }

    std::cout<<cnt;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    //std::cin>>t;
    while (t--) fc();
    return 0;
}