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.
【题意】
【思路】
【代码】
#include <iostream>
#include <algorithm>
#include <cstring>
#include<vector>
using namespace std;
const int maxn=1e5+10;
vector<int> G[maxn];//图的邻接表表示
vector<int> rG[maxn];//把边反向后的图
vector<int> vs;//后序遍历顺序的顶点列表
bool used[maxn];//访问标记
int cmp[maxn];//所属强连通分量的拓扑序
int a[maxn],b[maxn];
int V,N,M;
void add_edge(int from,int to)
{
G[from].push_back(to);
rG[to].push_back(from);
}
void dfs(int v)
{
used[v]=true;
for(int i=0;i<G[v].size();i++)
{
if(!used[G[v][i]])
dfs(G[v][i]);
}
vs.push_back(v);
}
void rdfs(int v,int k)
{
used[v]=true;
cmp[v]=k;
for(int i=0;i<rG[v].size();i++)
{
if(!used[rG[v][i]])
rdfs(rG[v][i],k);
}
}
int scc()
{
memset(used,0,sizeof(used));
vs.clear();
for(int v=0;v<V;v++)
{
if(!used[v]) dfs(v);
}
memset(used,0,sizeof(used));
int k=0;
for(int i=vs.size()-1;i>=0;i--)
{
if(!used[vs[i]]) rdfs(vs[i],k++);
}
return k;
}
int main()
{
cin>>N>>M;
V=N;
for(int i=0;i<M;i++)
{
cin>>a[i]>>b[i];
add_edge(a[i]-1,b[i]-1);
}
int n=scc();
//统计备选解的个数
int u=0,num=0;
for(int v=0;v<V;v++)
{
if(cmp[v]==n-1)
{
u=v;
num++;
}
}
memset(used,0,sizeof(used));
rdfs(u,0);//重用强连通分量分解的代码
for(int v=0;v<V;v++)
{
if(!used[v])//该点不可达
{
num=0;
break;
}
}
cout<<num<<endl;
return 0;
}
*强连通分量(模板)
ps:
参考书:挑战程序设计竞赛(第2版)