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.
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.
题意:有n只牛,然后牛A认为牛B受欢迎,牛B认为牛C受欢迎,这样牛A也认为牛C受欢迎,然后问有多少只牛被其他所有的牛认为他受欢迎。
分析:先用tarjan求出所有的强连通分量,然后将每个点缩成一个点,变成新的有向无环图,然后要使得有牛被其他的牛认为他受欢迎,就必须新建成的图的点只有一个出度为0,入果有两个以上的点出度为0,那么肯定没办法使有点牛被其他牛认为受欢迎。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn=10005;
vector <int> G[maxn];
int belong[maxn];
int dfn[maxn],low[maxn];
int ins[maxn],block,id;
int stack[maxn],tp;
int sz[maxn];//每个联通分量的规模,也就是点的数目
int n,m;
int a[50005],b[50005];
int out[maxn];//缩点后新的图的出度
void init(){
id=tp=block=0;
memset (dfn,0,sizeof (dfn));
memset (low,0,sizeof (low));
memset (sz,0,sizeof (sz));
memset (out,0,sizeof (out));
}
void tarjan(int u){
dfn[u]=low[u]=++id;
ins[u]=1;//表示在栈里面
stack[++tp]=u;//进栈
for (int i=0;i<G[u].size();i++){
int v=G[u][i];
if (!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if (ins[v])low[u]=min(low[u],dfn[v]);
}
if (low[u]==dfn[u]){
block++;//新的连通分量
int v;
do{
v=stack[tp--];
ins[v]=0;
belong[v]=block;
sz[block]++;
}while (u!=v);
}
}
int main ()
{
while (scanf ("%d%d",&n,&m)!=EOF){
init();
for (int i=0;i<m;i++){
scanf ("%d%d",&a[i],&b[i]);
G[a[i]].push_back(b[i]);//加边
}
for (int i=1;i<=n;i++){
if (!dfn[i]){
tarjan(i);
}
}
for (int i=0;i<m;i++){
int u=a[i],v=b[i];
if (belong[u]!=belong[v]){//如果不在一个连通分量
out[belong[u]]++;//出度加一
}
}
int ans=0;
int count=0;//出度为0的数目
for (int i=1;i<=block;i++){
if (out[i]==0){
ans+=sz[i];//将这个连通分量的点数加起来
count++;
}
}
if (count==1)printf ("%d\n",ans);//如果只有一个说明是符合的
else printf ("0\n");
}
return 0;
}