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.
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.
* 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
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define maxn 10008 #define edge 50008 int first[maxn],dfn[maxn],low[maxn],c[maxn],s[maxn],v[maxn],chudu[maxn],sum[maxn]; int vv[edge],nxt[edge]; int e,cnt,t,p; inline int min(int a,int b) { return a>b?b:a; } void addEdge(int u,int v) { vv[e] = v; nxt[e] = first[u]; first[u] = e++; }//边是单向的 void tarjan(int x) { dfn[x] = low[x] = ++cnt; s[++p] = x,v[x] = 1;/v[x]表示x入栈了 for(int i = first[x];i != -1;i = nxt[i]) { if(!dfn[vv[i]]) { tarjan(vv[i]); low[x] = min(low[x],low[vv[i]]); } else if(v[vv[i]])///如果这个点访问过,且还没出栈,出栈的不可能跟他在同一个连通分量 { low[x] = min(low[x],dfn[vv[i]]); } } if(low[x] == dfn[x])如果low[x] == dfn[x] ,那么以他为根的搜索树就是一个强连通分量 { int y; ++t; do{ y = s[p--]; v[y] = 0; c[y] = t; sum[t]++; } while(y!=x); } } int main() { //freopen("in.txt","r",stdin); int n,m; while(scanf("%d%d",&n,&m)==2) { memset(first,-1,sizeof(first)); memset(chudu,0,sizeof(chudu)); memset(sum,0,sizeof(sum)); cnt = e = p = t = 0; for(int i = 1;i <= m;i++) { int u,v; scanf("%d%d",&u,&v); addEdge(u,v); } for(int i=1;i<=n;i++) { if(!dfn[i]) { tarjan(i); } } for(int i=1;i<=n;i++) { for(int j = first[i];j != -1;j = nxt[j]) { if(c[i] != c[vv[j]]) { chudu[c[i]]++; } } } int num = 0,pos; for(int i=1;i<=t;i++) { if(chudu[i] == 0) { num++; pos = i; } } if(num == 1) printf("%d\n",sum[pos]); else printf("0\n"); } }