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

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. 

思路:

强联通分量分解实质上还是为了得到一个DAG(有向无环图)
进而可以得到一个拓扑排序后的图,从而确定某种指向关系
操作就是把图中的所有强联通分量(应该就是一个小回路吧)压缩成一个点
先用一个dfs() 去得到这个图个后序遍历  (就是靠近根的在右边靠近叶子的在左边)
然后有个比较重要的规律:一旦反向建图,如果按(从根到叶)遍历,每次rdfs递归后就能的到一个强连通分量;

#include<stdio.h>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
int u[51001],v[51010],first[51010],next[51000],k=1,z=0,m,n,sum=0;
int book[50110],cmp[50110],p;
vector<int > vs;
void add(int x,int y)
{
	u[k]=x,v[k]=y;
	next[k]=first[x],first[x]=k++;
}
void dfs(int x)
{
	int i;
	book[x]=1;
	for(i=first[x]; i!=-1; i=next[i])
		if(book[v[i]]==0) dfs(v[i]);
	vs.push_back(x);
}

void rdfs(int x,int num)
{
	int i;
	cmp[x]=num;
	book[x]=1;
	for(i=first[x]; i!=-1; i=next[i])
		if(book[v[i]]==0) rdfs(v[i],num);
}
int main()
{
	int j,i,a1,b1;
	scanf("%d %d",&n,&m);

	memset(first,-1,sizeof(first));
	for(i=1; i<=m; i++)
	{
		scanf("%d %d",&a1,&b1);
		add(a1,b1);
	}

	vs.clear();
	for(i=1; i<=n; i++)
		if(!book[i]) dfs(i);
	/*得到后序遍历:虽然遍历顺序不一样但是最后结果是一样的:每次都是 从叶到根的存储 */
	/*
	先向右递归返回时从右往左存:
	                     <-------
	              <------
	   	       <--
	       <----
	最后 根<--------------------叶
	*/

	k=1;
	memset(first,-1,sizeof(first));
	for(i=1; i<=m; i++) add(v[i],u[i]);/*反向建图*/

	z=0;
	memset(book,0,sizeof(book));
	for(i=vs.size()-1; i>=0; i--)
		if(!book[vs[i]])
			rdfs(vs[i],++z);/*编号:同一个强联通分量共用一个z*/

	for(i=1; i<=n; i++)
		if(cmp[i]==z)
			sum++,p=i;/*拓扑序的最后一个强连通分量就是题解*/

	memset(book,0,sizeof(book));
	rdfs(p,0);/*用rdfs判断整个图是否连通*/
	for(i=1; i<=n; i++)
		if(book[i]==0)
		{
			sum=0;
			break;
		}

	printf("%d\n",sum);
	return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值