Popular Cows ( tarjan 模板)

Every cow’s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
Input

  • Line 1: Two space-separated integers, N and M

  • Lines 2…1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
    Output

  • Line 1: A single integer that is the number of cows who are considered popular by every other cow.
    Sample Input
    3 3
    1 2
    2 1
    2 3
    Sample Output
    1
    Hint
    Cow 3 is the only cow of high popularity.

题意: 给定n头牛,接下来m行数据,每行两个数a和b,代表a认为b受欢迎,求有多少头牛被认为是受欢迎的,a认为b受欢迎,b认为c受欢迎,则a认为c受欢迎。

思路:因为这道题有传递性,所以在有向图上找出强连通子图,可以发现每个子图中的奶牛一定互相喜欢,所以把每一个强连通子图找出,缩点,然后整个图就变换成了有向无环图。因为同一点需要受到所有其他奶牛的喜欢,所以他不能喜欢任意除了自己这个联通子图的牛的其他牛,所以统计一下是否存在出度为零的点就好了,但是如果存在两个或两个以上的出度为零的点,那么就说明这几个子图中奶牛各自都无法喜欢到其他样子的子图中的奶牛,输出零。

代码:

#include<iostream>
/*因为统一头牛需要受到其他所有奶牛的喜欢,
那么他就不能喜欢除了自己这个连通子图的牛的其他牛,
所以统计是否存在出度为零的点就行了 
*/ 
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=5e4+5,maxm=5e4+5;
int to[maxn],nex[maxn],fir[maxn];
int col,num,dfn[maxm],low[maxn],de[maxn],si[maxn];
int tot=0,co[maxn],n,m;
int top,st[maxn];
inline void ins(int x,int y)//  添加 一条 x->y 的边 
{
	to[++tot]=y;
	nex[tot]=fir[x];
	fir[x]=tot;
}
void tarjan(int u)// 缩点 
{
	dfn[u]=low[u]=++num;
	st[++top]=u;//  将 u 入栈  
	for(int i=fir[u];i;i=nex[i])// 枚举 每条边 
	{
		int v=to[i];
		if(!dfn[v])
		{
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}
		else
		if(!co[v])// 如果节点v 还在栈中 即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;// 将st[top] 退栈, 为该强连通分量 中一个顶点 
			--top;
		}
		--top;// 将u 退栈 
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1,x,y;i<=m;i++)
	{
		scanf("%d%d",&x,&y);
		ins(y,x);// 反向建边, 统计入度 
	}
	for(int i=1;i<=n;i++)
	{
		if(!dfn[i])
		tarjan(i);
	}
	for(int i=1;i<=n;i++)
	for(int j=fir[i];j;j=nex[j])// 统计入度 
	if(co[i]!=co[to[j]])
	de[co[to[j]]]++;
	int ans=0,u=0;
	for(int i=1;i<=col;i++)
	if(!de[i])
	ans=si[i],u++;
	if(u==1)
	printf("%d\n",ans);
	else
	printf("0\n");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值