图论-强连通分量-(百练)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.
输入

  • 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.

输出

  • Line 1: A single integer that is the number of cows who are considered popular by every other cow.

样例输入
3 3
1 2
2 1
2 3

样例输出
1

有n头奶牛,给出m对奶牛之间的仰慕关系,求有多少头奶牛能被所有奶牛仰慕,只有这头牛被所有的牛都仰慕它才是最受欢迎的牛。

解题思路:
①建图:建有向图G
②求强连通分量scc:kosaraju算法,G,rG
③最后一个强连通分量scc内所有节点能否到到其它所有节点
④若能则输出scc的大小,否则输出0

链接:图论-有向图中的强连通片

在这里插入图片描述
在这里插入图片描述

Code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;
struct T{
	int id,fw;//节点id  节点所在的强连通分量编号 
};
vector<vector<int>>G,rG;//正向图 反向图 
vector<bool>visited;
vector<bool>visRG;
vector<T>ZC;
vector<int>postOrder;
vector<int>sccNo;
int sccCnt;
int N,M,sum=0;
bool cmp(T e1,T e2){
	return e1.fw>e2.fw;
}
void dfs1(int x){//求出拓扑排序 
	visited[x]=true;
	for(auto i : G[x])
		if(!visited[i]) 
		   dfs1(i);
	postOrder.push_back(x);
}
void dfs2(int x){//划分强连通分量 
	sccNo[x]=sccCnt;
	ZC.push_back({x,sccCnt});//对每个节点id 和 所在强连通分量的标号 进行存储 
	for(auto i : rG[x])
		if(sccNo[i]==0)
			dfs2(i);
}
void kosaraju(){
	for(int i=1;i<=N;i++){//把所有的边都访问一遍 
		if(!visited[i])
			dfs1(i);
	}
	reverse(postOrder.begin(),postOrder.end());
	for(auto x:postOrder){
		if(sccNo[x]==0){
			++sccCnt;
			dfs2(x);
		}
	}
} 
void rGdfs(int x){//对x进行深搜 
	visRG[x]=true;
	for(auto e : rG[x])
		if(!visRG[e])
			rGdfs(e);
}
bool check(int x){//检查x点是否可以到达rG图的所有点 若都可到达则为受欢迎的牛 
	rGdfs(x);
	for(int i=1;i<=N;i++) 
		if(!visRG[i])
			return false;
	return true;
}
int main(){
	cin>>N>>M;
	G.resize(N+1);
	rG.resize(N+1);
	visited.resize(N+1);
	sccNo.resize(N+1);
	visRG.resize(N+1);
	while(M--){
		int x,y;
		cin>>x>>y;
		G[x].push_back(y);
		rG[y].push_back(x);
	}	
	kosaraju();
	sort(ZC.begin(),ZC.end(),cmp);//把节点的连通分量的编号从大到小排列 
	for(int i=0;i<ZC.size();i++){
		if(ZC[i].fw==sccCnt){//如果i节点的连通分量标号是最大的连通分量标号  说明它是最后一个连通分量内的节点 
			if(!check(ZC[i].id)){
				break;
			}
			sum++;
		}else//如果i节点的连通分量标号不是最大的连通分量标号 即使从它开始搜 也到不了最后一个连通分量内 所以退出即可 
			break;//只有这个节点深搜遍历到所有节点才是最受欢迎的牛 
	} 
	cout<<sum;
	return 0;
} 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值