P2341 [USACO03FALL / HAOI2006] 受欢迎的牛 G
判断强连通的关键是dfn与low。
dfn记录的是节点dfs搜索时的dfs序,而low则是记录表示这个点以及其子孙节点连的所有点中dfn最小的值。
关键节点即为dfn和low相等的节点。
colors则为节点染色:每次找到关节节点后,在栈中其前面的所有节点构成了一个强连通块。
而colors则是将这些节点记录为同一种颜色以表示他们在一个强连通块中
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<math.h>
#include <stack>
#include<map>
#include<stdlib.h>
#include<queue>
#define LL long long
#define re register
using namespace std;
const int N=5e5+10,M=1e4+10,inf=0x3f3f3f3f;
const LL INF=1e18,mod=998244353;
int to[N],nxt[N],head[N],ecnt;
int col,num,dfn[M],low[M],de[M],si[M];
int co[M],top,st[M];
int n,m;
inline void add(int x,int y) {
to[++ecnt]=y;
nxt[ecnt]=head[x];
head[x]=ecnt;
}
inline void Tarjan(int u) {
dfn[u]=low[u]=++num;
st[++top]=u;
for(int i=head[u]; i; i=nxt[i]) {
int v=to[i];
if(!dfn[v]) {
Tarjan(v);
low[u]=min(low[u],low[v]);
} else if(!co[v]) {
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u]) {
co[u]=++col;
++si[col];
while(st[top]!=u) {
++si[col];
co[st[top]]=col;
--top;
}
--top;
}
}
int main() {
int x,y;
scanf("%d%d",&n,&m);
for(int i=1; i<=m; i++) {
scanf("%d%d",&x,&y);
add(y,x);
}
for(int i=1; i<=n; i++) {
if(!dfn[i])Tarjan(i);
}
for(int i=1; i<=n; i++) {
for(int j=head[i]; j; j=nxt[j]) {
if(co[i]!=co[to[j]])de[co[to[j]]]++;
}
}
int ans=0,op=0;
for(int i=1; i<=col; i++) {
if(!de[i])ans=si[i],op++;
}
if(op==1)printf("%d",ans);
else printf("0");
return 0;
}