对于缩点后得到的DAG,我们求出入度为0的强连通分量的个数,即为最少的需要添加的边。(注意判断首都所在的强连通分量的入度)
#include <bits/stdc++.h>
using namespace std;
const int N=5e3+5;
int n,m,s,u[N],v[N],ans,du[N];
int now,top,col,dfn[N],low[N],sta[N],color[N];
int cnt,head[N];
struct edge{int next,to;}e[N<<1];
inline void add(int u,int v)
{
cnt++;
e[cnt].next=head[u];
e[cnt].to=v;
head[u]=cnt;
}
void tarjan(int u)
{
dfn[u]=low[u]=++now;
sta[++top]=u;
for (register int i=head[u]; i; i=e[i].next)
if (!dfn[e[i].to])
{
tarjan(e[i].to);
low[u]=min(low[u],low[e[i].to]);
}
else if (!color[e[i].to]) low[u]=min(low[u],low[e[i].to]);
if (dfn[u]==low[u])
{
col++;
while (sta[top]!=u) color[sta[top]]=col,top--;
color[sta[top]]=col,top--;
}
}
int main(){
scanf("%d%d%d",&n,&m,&s);
for (register int i=1; i<=m; ++i) scanf("%d%d",&u[i],&v[i]),add(u[i],v[i]);
for (register int i=1; i<=n; ++i) if (!dfn[i]) tarjan(i);
for (register int i=1; i<=m; ++i) if (color[u[i]]!=color[v[i]]) du[color[v[i]]]++;
for (register int i=1; i<=col; ++i) if (!du[i] && i!=color[s]) ans++;
printf("%d\n",ans);
return 0;
}