Description
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
【分析】
规定受欢迎的牛是被指向的点,然后开干。具体做法是先用tarjan算法缩点,找出出度为0的点即可。如果有多个,则它们无法互相到达,所以答案是0
【代码】
//popular cows
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
#define fo(i,j,k) for(i=j;i<=k;i++)
#define mx 100000000
using namespace std;
vector <int> f[10001];
stack <int> s;
bool in[10001],flag[10001];
int time[10001],low[10001],many[10001],cun[10001],x[50001],y[50001];
int n,m,t,num,hm;
void dfs(int u)
{
int i,j,k,v,c;
low[u]=time[u]=++t; //发现时间chuo
in[u]=1; //进栈标记
s.push(u); //进栈
c=f[u].size()-1;
fo(i,0,c)
if(!time[f[u][i]])
{
dfs(f[u][i]);
low[u]=min(low[u],low[f[u][i]]);
}
else if(in[u])
low[u]=min(low[u],time[f[u][i]]);
if(time[u]==low[u])
{
num++;
do
{
v=s.top();
in[v]=0;
cun[v]=num;
s.pop();
}while(u!=v);
}
}
int main()
{
int i,j,k,u,v,d;
scanf("%d%d",&n,&m);
fo(i,1,m)
{
scanf("%d%d",&x[i],&y[i]);
f[x[i]].push_back(y[i]);
}
fo(i,1,n)
if(!time[i]) dfs(i);
fo(i,1,m)
if(cun[x[i]]!=cun[y[i]]) //如果两个相连点不处于同一强连通分量中
flag[cun[x[i]]]=true; //缩点,表示有出度
fo(i,1,n) many[cun[i]]++;
fo(i,1,num)
if(!flag[i]) //若没有出度
{
k=many[i];
hm++;
}
if(hm==1) printf("%d\n",k);
else printf("0\n");
return 0;
}