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 个点和 M 条边,求大小 >1 的强连通分量的个数。(省略多余描述)(2 ≤ N ≤ 10000,1 ≤ M ≤ 50000)
代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<iostream>
#include<ctype.h>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<stdlib.h>
#include<queue>
#include<stack>
#define ll long long
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 1e4+5;
vector<int> g[maxn];
stack<int>st;
int dfn[maxn],low[maxn],vis[maxn],id[maxn],sum[maxn];
int cnt,k,n,niu=0,m;
void init()
{
cnt=k=0;
for(int i=0;i<=n;i++)
{
g[i].clear();
}
while(!st.empty())
{
st.pop();
}
mem(dfn,0);
mem(low,0);
mem(vis,0);
mem(id,0);
mem(sum,0);
}
void tarjan(int u)
{
dfn[u]=low[u]=++k;
st.push(u);
vis[u]=1;
int len=g[u].size();
for(int i=0;i<len;i++)
{
int v=g[u][i];
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(vis[v])
{
low[u]=min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u])
{
cnt++;
int v;
do{
v=st.top();
st.pop();
vis[v]=0;
id[v]=cnt;
}while(u!=v);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int u, v;
init();
while(m --)
{
scanf("%d %d", &u, &v);
g[u].push_back(v);
}
for (int i = 1;i <= n;i++)
{
if(!dfn[i]) tarjan(i);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=cnt;j++)
{
if(id[i]==j)
{
sum[j]++;
}
}
}
for(int i=1;i<=cnt;i++)
{
if(sum[i]>1)
{
niu++;
}
}
printf("%d",niu);
}
return 0;
}