BZOJ 1051: [HAOI2006]受欢迎的牛

仅解释一下tarjan缩点的模板。

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
const int N=1e4+5,M=5e4+5;
int n,m,u,v,ans,sum;
int du[N];
int now,top,col,dfn[N],low[N],sta[N],si[N],color[N];
int cnt,head[N];
struct edge{int next,to;}e[M<<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]);
		//这里一定要写low[e[i].to]的 
	}
	else if (!color[e[i].to]) low[u]=min(low[u],low[e[i].to]);
	//如果出现了dfn[e[i].to] && !color[e[i].to]的情况,那么当前u肯定是一个环中的编号不是最小的一个点
	//而low[u]的作用是判断是否和dfn[u]相同,如果相同就说明当前堆积在栈里的所有节点是在同一个环里的
	//既然当前得到的low[u],不管是min(low[u],dfn[e[i].to])还是min(low[u],low[e[i].to]),都不会等于dfn[u]了
	//所以相当于它的作用已经达到了,就不用管它到底是什么值了。 
	//因为你想要的只是:low[u]!=dfn[u]就行了。 而low[u]到底是多少,是没意义的。
	if (dfn[u]==low[u])
	{
		col++;
		while (sta[top]!=u) color[sta[top]]=col,si[col]++,top--;
		color[sta[top]]=col,si[col]++;
		top--;
	}
}

int main(){
	scanf("%d%d",&n,&m);
	for (register int i=1; i<=m; ++i) scanf("%d%d",&u,&v),add(u,v);
	for (register int i=1; i<=n; ++i) if (!dfn[i]) tarjan(i);
	for (register int u=1; u<=n; ++u)
	for (register int i=head[u]; i; i=e[i].next) if (color[u]!=color[e[i].to]) du[color[u]]++;
	for (register int i=1; i<=col; ++i) if (!du[i]) sum++,ans=si[i];
	if (sum==1) printf("%d\n",ans);
	else printf("%d\n",0);
return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值