POJ2186 Popular Cows 强连通分量

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 30459 Accepted: 12365

Description

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

题意:有n头牛,每头牛都有一个自己崇拜的牛,当A崇拜B且B崇拜C是那么A也崇拜C,先给出崇拜关系,问你有多少其他所有牛都崇拜的牛。

思路:在一个强连通分量内,任意一头牛一定会被该分量其他牛所崇拜,因此先求出所有的强连通分量,然后对其进行缩点并求出所有点的出度,当只有一个出度为0是,该分量内的牛的数量,否则输出0。

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<vector>
using namespace std;
const int maxm=10006;
int vis[maxm]={0},num[maxm]={0},dfn[maxm]={0},low[maxm]={0},p[maxm],belong[maxm]={0},sum=1,id=1;
int g[maxm]={0},f[maxm]={0};
vector<int>v[maxm];
stack<int>s;
typedef struct
{
	int x,y;
}H;
H a[maxm];
void tarjian(int x);
int find(int k);
int main()
{
	int i,j,k,n,m,x,y;
	memset(p,-1,sizeof(p));
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;i++)
	{
		scanf("%d%d",&x,&y);
		v[x].push_back(y);
	}
	for(i=1;i<=n;i++)
	{
		if(!dfn[i])
			tarjian(i);
	}
	for(i=1;i<=n;i++)
	{
		for(j=0;j<v[i].size();j++)
		{
			int xx=v[i][j];
			if(belong[xx]!=belong[i])
				g[belong[i]]+=1;
		}
	}
	int d,ans=0;
	for(i=1;i<sum;i++)
	{
		if(g[i]==0)
		{
			d=num[i];
			ans++;
		}
		if(ans>1)
			break;
	}
	if(ans==1)
		printf("%d\n",d);
	else
		printf("0\n");	
	return 0;
}
void tarjian(int x)
{
	int i,j;
	s.push(x);vis[x]=1;low[x]=dfn[x]=id++;
	for(j=0;j<v[x].size();j++)
	{
		int xx=v[x][j];
		if(!dfn[xx])
		{
			tarjian(xx);
			low[x]=min(low[x],low[xx]);
		}
		else if(vis[xx])
			low[x]=min(low[x],dfn[xx]);
	}
	if(dfn[x]==low[x])
	{
		while(s.size())
		{
			int xx=s.top();s.pop();
			num[sum]++;
			vis[xx]=0;
			belong[xx]=sum;
			if(xx==x)
				break;
		}
		sum++;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值