强连通分量。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#define maxv 10050
#define maxe 50050
using namespace std;
struct edge
{
int v,nxt;
}e[maxe];
stack <int> s;
int n,m,a,b,times=0,dfn[maxv],low[maxv],nume=0,g[maxv];
int uuu[maxv];
bool vis[maxv],ins[maxv];
int hash[maxv],num[maxv],cnt=0;
void addedge(int u,int v)
{
e[++nume].v=v;
e[nume].nxt=g[u];
g[u]=nume;
}
void tarjan(int x)
{
++times;
dfn[x]=times;
low[x]=times;
vis[x]=true;
ins[x]=true;
s.push(x);
for (int i=g[x];i;i=e[i].nxt)
{
int v=e[i].v;
if (vis[v]==false)
{
tarjan(v);
low[x]=min(low[x],low[v]);
}
else if (ins[v]==true)
low[x]=min(low[x],dfn[v]);
}
if (dfn[x]==low[x])
{
int head,lll=0;cnt++;
do
{
head=s.top();
ins[head]=false;
s.pop();
hash[head]=cnt;
lll++;
}while (head!=x);
uuu[cnt]=lll;
}
}
int main()
{
memset(num,0,sizeof(cnt));
memset(g,0,sizeof(g));
memset(vis,false,sizeof(vis));
cnt=0;
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
addedge(a,b);
}
for (int i=1;i<=n;i++)
{
if (vis[i]==false)
tarjan(i);
}
for (int ee=1;ee<=n;ee++)
for (int i=g[ee];i;i=e[i].nxt)
{
int v=e[i].v;
if (hash[ee]!=hash[v])
num[hash[ee]]++;
}
int ans=0;
for (int i=1;i<=cnt;i++)
{
if (num[i]==0)
ans=ans+uuu[i];
}
printf("%d
",ans);
return 0;
}