【强连通】P2341 [USACO03FALL / HAOI2006] 受欢迎的牛 G

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值