Poj2186 Popular Cows

题目描述:

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 32599 Accepted: 13280

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

Hint

Cow 3 is the only cow of high popularity. 

Source


题目大意

给定一些关系(x,y)代表牛x认为牛y是受欢迎的,如果牛x认为牛y受欢迎且牛y认为牛z受欢迎,那么牛x也认为牛z受欢迎。要求输出被所有牛认为是受欢迎的牛的个数。


思路:

根据输入的关系建一张图,如果牛x认为牛y受欢迎,那么就在x、y间连一条有向边(x指向y)。

然后用tarjan算法去环缩点,因为在一个环中,任意一头牛都被这个环里所有的牛喜欢。

在新图中,被所有点指向的点的出度为0(因为此时图中无环),所以就是要求出出度为0的点。但如果存在2个及以上的出度为0的点,就没有最受欢迎的牛。


代码:

#include<cstdio>
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

int n,m;
vector<int> a[10010];

int color[10010]= {0},num=0;
int total[10010]= {0};
stack<int> s;
int dfn[10010]= {0},low[10010]= {0},clock=0;
int tarjan(int x) {
	s.push(x);
	dfn[x]=low[x]=++clock;
	for(int i=0; i<a[x].size(); i++) {
		int y=a[x][i];
		if(dfn[y]==0) {
			low[x]=min(low[x],tarjan(y));
		} else if(color[y]==0){
			low[x]=min(low[x],dfn[y]);
		}
	}

	if(low[x]==dfn[x]) {
		num++;
		while(s.top()!=x) {
			color[s.top()]=num;
			s.pop();
			total[num]++;
		}
		total[num]++;
		color[x]=num;
		s.pop();
	}
	return low[x];
}

int main() {

	scanf("%d%d",&n,&m);
	for(int i=1; i<=m; i++) {
		int x,y;
		scanf("%d%d",&x,&y);
		a[x].push_back(y);
	}

	for(int i=1; i<=n; i++) {
		if(color[i]==0)
			tarjan(i);
	} 
	
	//统计个数 
	int in[10010]={0};
	for(int i=1; i<=n; i++) {
		for(int j=0;j<a[i].size();j++){
			if(color[i]!=color[a[i][j]]){
				in[color[i]]++;
			}
		}
	}
	
	int ans=0;
	bool flag=false;
	for(int i=1;i<=num;i++){
		if(!in[i]){
			if(flag==true){
				printf("0");
				return 0;
			}else{
				flag=true;
				ans=i;
			}
		}
	}
	printf("%d",total[ans]);
	
	return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值