QQ联系我

BZOJ 1051: [HAOI2006]受欢迎的牛

1051: [HAOI2006]受欢迎的牛

Time Limit: 10 Sec  Memory Limit: 162 MB

Submit: 6559  Solved: 3441

[Submit][Status][Discuss]

Description

  每一头牛的愿望就是变成一头最受欢迎的牛。现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎。 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认为牛C受欢迎。你的任务是求出有多少头牛被所有的牛认为是受欢迎的。

Input

  第一行两个数N,M。 接下来M行,每行两个数A,B,意思是A认为B是受欢迎的(给出的信息有可能重复,即有可能出现多个A,B)

Output

  一个数,即有多少头牛被所有的牛认为是受欢迎的。

Sample Input

3 3
1 2
2 1
2 3

Sample Output

1

HINT

100%的数据N<=10000,M<=50000

题解

用tarjan求强联通,如果有多个DAG图,那么答案一定是0,因为一个DAG图中的点无法到达另一个DAG图中的点。

如果只有一个DAG图,对于一个强联通内的点,一定能互相喜欢,很容易想到,若DAG图中出度为0的强联通只有一个,那么该强联通的点一定能被所以的点喜欢,若有多个出度为0的强联通,那么答案为0,因为两个出度为0的强联通不能相互喜欢。

因为多个DAG的情况也存在多个出度为0的强联通,所以一起讨论即可。

如果最终只有一个出度为0的强联通,则输出他内部点的个数,其他情况均输出0。

代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
const int N=10005,M=50005;
int n,m,k=1,cnt,tot,ans;
int head[N],dfn[N],low[N],vis[N],belong[N],sum[N],out[N];
struct edge{
	int u,v,next;
}e[M];
void addedge(int u,int v){
	e[k]=(edge){u,v,head[u]};
	head[u]=k++;
}
stack<int>st;
void dfs(int u){
	dfn[u]=++cnt;
	low[u]=cnt;
	st.push(u);
	int v;
	for(int i=head[u];i;i=e[i].next){
		v=e[i].v;
		if(!dfn[v]){
			dfs(v);
			low[u]=min(low[u],low[v]);
		}
		else if(!vis[v]){
			low[u]=min(low[u],dfn[v]);
		}
	}
	if(dfn[u]==low[u]){
		tot++;
		while(1){
			v=st.top();
			st.pop();
			belong[v]=tot;
			vis[v]=1;
			sum[tot]++;
			if(v==u)break;
		}
	}
}
int main(){
	scanf("%d%d",&n,&m);
	int u,v;
	for(int i=1;i<=m;i++){
		scanf("%d%d",&u,&v);
		addedge(u,v);
	}
	for(int i=1;i<=n;i++){
		if(!dfn[i]){
			dfs(i);
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=head[i];j;j=e[j].next){
			v=e[j].v;
			if(belong[i]!=belong[v]){
				out[belong[i]]++;
			}
		}
	}
	for(int i=1;i<=tot;i++){
		if(out[i]==0&&ans){
			printf("0\n");
			return 0;
		}
		if(out[i]==0)ans=sum[i];
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2017-10-23 17:50  czy020202  阅读(114)  评论(0编辑  收藏  举报