POJ - 2186 Popular Cows(强连通分量+缩点)

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条有向边,问除它之外,其它n-1个点都能走到它的点的个数。
    (还是菜,缩完点后只看出度就行了,如果有多个点出度为0,则肯定没答案;否则,直接输出该缩点(即该强连通分量)的点的个数)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#define LL long long 
using namespace std;
const int maxn=1e4+10;
const int maxm=5e4+10;
struct node
{
	int to,next;
}E[maxm];
int head[maxn],dfn[maxn],low[maxn],sta[maxn],color[maxn];
int num[maxn],out[maxn];
bool vis[maxn];
int cnt,top,sum,id;
void Init()
{
	memset(head,-1,sizeof(head));
	cnt=top=sum=id=0;
}
void add(int u,int v)
{
	E[cnt].to=v;
	E[cnt].next=head[u];
	head[u]=cnt++;
}
void tarjan(int u)
{
	dfn[u]=low[u]=++id;
	sta[++top]=u;
	vis[u]=1;
	for(int i=head[u];i!=-1;i=E[i].next)
	{
		int v=E[i].to;
		if(!dfn[v])
		{
			tarjan(v);
			low[u]=min(low[u],low[v]);	
		}
		else if(vis[v])
		{
			low[u]=min(low[u],low[v]);
		}
	}
	if(dfn[u]==low[u])
	{
		int s=1;
		color[u]=++sum;
		while(sta[top]!=u)
		{
			color[sta[top]]=sum;
			vis[sta[top--]]=0;
			s++;	
		}
		vis[sta[top--]]=0;
		num[sum]=s;
	}
	
}
int main(void)
{
	Init();
	int n,m,u,v;
	scanf("%d%d",&n,&m);
	for(int i=0;i<m;i++)
	{
		scanf("%d%d",&u,&v);
		add(u,v);
	}
	for(int i=1;i<=n;i++)
	{
		if(!dfn[i])
		  tarjan(i);
	}
	int ans=1;
	for(int i=1;i<=n;i++)
	{
		for(int j=head[i];j!=-1;j=E[j].next)
		{
			if(color[i]!=color[E[j].to])
			{
               out[color[i]]++;
			}
		}
	}
	int count=0;
	//缩完点后,如果只有一个出度为0的点,说明存在答案,且为该点所包含的点的个数 
	for(int i=1;i<=sum;i++)
	{
		if(out[i]==0)
		 ans=num[i],count++;
	}
	if(count!=1)
		ans=0;
    printf("%d\n",ans);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值