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

猜你喜欢

转载自blog.csdn.net/KIKO_caoyue/article/details/84282173
今日推荐