Tarjan缩点【洛谷P2341】

传送门:https://www.luogu.org/problemnew/show/P2341

这题很简单,不知道为什么是提高组的题...

主要思路就是先tarjan缩点,然后在DAG上找出度为0的点,如果只有一个出度为0的点,那么这个点就是的大小就是受欢迎的牛的数目。如果有两个及以上个点的出度为0,那么不存在明星牛。

下面是代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4+7;
vector<int> G[maxn];
int low[maxn],dfn[maxn];
int ins[maxn];
int color[maxn],sum[maxn];
int de[maxn];
stack<int> s;
int n,m;
int cnt = 0;
int tot = 0;
void tarjan(int x)
{
	low[x] = dfn[x] = ++cnt;
	s.push(x);
	ins[x] = 1;
	for(int i=0;i<G[x].size();i++)
	{
		int v = G[x][i];
		if(!dfn[v])
		{
			tarjan(v);
			low[x] = min(low[x],low[v]);
		}
		else if(ins[v])
		{
			low[x] = min(low[x],dfn[v]);
		}
	} 
	if(low[x]==dfn[x])
	{
		tot++;
		while(true)
		{
			int tmp = s.top();
			s.pop();
			sum[color[tmp]=tot]++;
			ins[tmp] = 0;
			if(tmp==x) break;
		}
	}
}
int main()
{
	cin>>n>>m;
	int x,y;
	for(int i=0;i<m;i++)
	{
		cin>>x>>y;
		G[x].push_back(y);
	}
	for(int i=1;i<=n;i++)
	{
		if(!dfn[i])
		{
			tarjan(i);
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=0;j<G[i].size();j++)
		{
			int v = G[i][j];
			if(color[i]!=color[v])
			{
				de[color[i]]++;
			}
		}
	}
	int ans = 0;
	for(int i=1;i<=tot;i++)
	{
		if(!de[i])
		{
			if(ans)
			{
				ans = 0;
				break;
			}
			ans = sum[i];
		}
	}
	cout<<ans<<endl;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值