有向无环图中,如果有且仅有一个点的出度为0,则所有的点都可以到达它。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
const int inf =0x3ffffff;
const int maxn=10005;//点数
struct edge
{
int from,to,w,next;
}e[50005];//边数
stack<int>pq;
int head[maxn];
int instack[maxn];//是否在栈中
int dfn[maxn];//同时可用于判断是否遍历过
int low[maxn];
int color[maxn],du[maxn];
int n,m,t,index,se;//n个点,m条边,t用来生成边的标号,index用来生成点的标号
void init()//建图前运行init
{
t=0;
index=0;
se=0;
memset(head,-1,sizeof(head));
memset(instack,0,sizeof(instack));
memset(dfn,-1,sizeof(dfn));
memset(low,-1,sizeof(low));
memset(color,-1,sizeof(color));
memset(du,0,sizeof(du));
while(!pq.empty())
pq.pop();
}
void add(int i,int j,int w)
{
e[t].from=i;
e[t].to=j;
e[t].w=w;
e[t].next=head[i];
head[i]=t++;
}
void tarjan(int u)
{
dfn[u]=low[u]=++index;
pq.push(u);
instack[u]=1;
for(int i=head[u];i!=-1;i=e[i].next)
{
if(dfn[e[i].to]==-1)
{
tarjan(e[i].to);
low[u]=min(low[u],low[e[i].to]);
}
else if(instack[e[i].to]==1)
{
low[u]=min(low[u],dfn[e[i].to]);
}
}
if(dfn[u]==low[u])
{
int v;
v=pq.top();//从这个v开始为强连通分量的一个
color[v]=se;
pq.pop();
instack[v]=0;
while(v!=u)
{
v=pq.top();
color[v]=se;
pq.pop();
instack[v]=0;
}
se++;
}
}
int main()
{
int a,b,st;
int i,j;
scanf("%d%d",&n,&m);
init();
while(m--)
{
scanf("%d%d",&a,&b);
add(a,b,0);
}
for(i=1;i<=n;i++)
{
if(dfn[i]==-1)
tarjan(i);
}
for(i=1;i<=n;i++)
for(j=head[i];j!=-1;j=e[j].next)
{
if(color[e[j].from]!=color[e[j].to])
{
du[color[e[j].from]]++;
}
}
int temp,cnt=0,ans=0;;
for(i=0;i<se;i++)
{
if(du[i]==0)
{
cnt++;
temp=i;
}
}
if(cnt==1)
{
for(i=1;i<=n;i++)
if(color[i]==temp)
ans++;
printf("%d\n",ans);
}
else
{
printf("0\n");
}
//system("pause");
return 0;
}